Using the prepare()
method, the values for the query are passed through parameters, which are partially handled by the query. Queries using this method are preferable when the desired parameters are dynamic.
With the query()
method, the queries are executed along with the values passed in it, without any internal treatments, and the part of treating these values in order to make them safe for the query, is left to the choice of the programmer.
Using prepared statments with
PDO
you can use two types of placeholders or parameters:
- The question mark (?).
- The colon followed by the desired parameter name (: name).
You can not use the two types of parameters in the same query SQL , you must choose one, and only use this parameter in the current query, and the values passed must not be executed directly in the query.
Another thing is the fact that PDO will emulate the prepared statments for the drivers not supported by it natively, and not all drivers support both types.
Using the question mark (? ):
$query = DB::getConn()->prepare('select * from tabela where id in (?)');
$query->execute(array(1));
Using the Named Parameter (: name ):
$query = DB::getConn()->prepare('select * from tabela where id in (:nome)');
$query->execute(array(':nome'=>1));
Using the question mark for an unknown number of parameters:
$values = array(1,2,3,4,5,6,...n);
foreach ($values as $val)
{
$params[] = '?';
}
$query = DB::getConn()->prepare('select * from tabela where id in ('.implode(",", $params).')');
$query->execute($values);
Multiple entries for 2 specific fields in the SQL table:
foreach($values as $id=>$val){
$params[] = '(?, ?)';
$binds['campo1' . $i] = $val;
$binds['campo2' . $i] = $val;
$i++;
}
$sql = "INSERT INTO x (campo1, campo2) VALUES ". implode(",", $params);
Or, several named parameters for 2 specific fields of the SQL table:
foreach($values as $id=>$val){
$params[] = '(:campo1' . $i . ', :campo2' . $i . ')';
$binds['campo1' . $i] = $val;
$binds['campo2' . $i] = $val;
$i++;
}
$sql = "INSERT INTO x (campo1, campo2) VALUES ". implode(",", $params);
Some references:
Writing MySQL script with PHP and PDO
PDO Prepared Statments - PHP.net
PDO Query - PHP.net