User Tools

Site Tools


pdo:insert_statements

Differences

This shows you the differences between two versions of the page.

Link to this comparison view

Next revision
Previous revision
pdo:insert_statements [2016/10/14 09:27] – created peterpdo:insert_statements [2020/07/15 09:30] (current) – external edit 127.0.0.1
Line 8: Line 8:
 </code> </code>
  
- +===== Preparing Statements using SQL functions =====
-You may ask how do you use SQL functions with prepared statements. I've seen people try to bind functions into placeholders like so:+
  
 <code php> <code php>
Line 58: Line 57:
 </code> </code>
  
 +
 +Note we used **bindValue** and not **bindParam**.  Trying to bind a parameter by reference will generate a Fatal Error and this cannot be caught by PDOException either.
 +
 +
 +===== Executing prepared statements in a loop =====
 +
 +Prepared statements excel in being called multiple times in a row with different values.  Because the sql statement gets compiled first, it can be called multiple times in a row with different arguments, and you'll get a big speed increase vs calling mysql_query over and over again!
 +
 +Typically this is done by binding parameters with **bindParam**.  bindParam is much like bindValue except instead of binding the value of a variable, it binds the variable itself, so that if the variable changes, it will be read at the time of execute.
 +
 +<code php>
 +<?php
 +$values = array('bob', 'alice', 'lisa', 'john');
 +$name = '';
 +$stmt = $db->prepare("INSERT INTO table(`name`) VALUES(:name)");
 +$stmt->bindParam(':name', $name, PDO::PARAM_STR);
 +foreach($values as $name) {
 +  $stmt->execute();
 +}
 +</code>
pdo/insert_statements.1476437251.txt.gz · Last modified: 2020/07/15 09:30 (external edit)

Donate Powered by PHP Valid HTML5 Valid CSS Driven by DokuWiki