Using the method prepare()
, the values for the query are passed through parameters, which are dealt with in part by the query. Queries using this method are preferred when the desired parameters are dynamic.
With the method query()
the queries are executed together with the values passed in it, without any internal treatments, and the part dealing with these values so as to make them safe for the query, are left to the programmer’s choice.
Using the Prepared statments with the PDO
can use two types of placeholders or parameters:
- The question mark ( ? ).
- The two points followed by the name of the desired parameter ( :name ).
The two types of parameters cannot be used in the same query SQL, one should be chosen, and only use this parameter in the current query, and the values passed should not be executed directly in the query.
Another thing is the fact that the PDO will emulate the Prepared statments for 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 a number of unknown 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 SQL table fields:
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
Is using the PDO?
– rray
Yes @rray all for security
– ndroid