Skip to content Skip to sidebar Skip to footer

Mysql In Clause Parameterization In Php, Python

I'm used to doing something like the following for my queries: $array = array(123,456,10,57,1024,768); //random data $sql = 'select * from table where field in('.implode(',',$array

Solution 1:

Using PDO prepared statements:

$placeholders = str_repeat('?, ', count($array)-1) . '?';
$stmt = $pdo->prepare("SELECT * FROM table WHERE field IN ($placeholders)");
$stmt->execute($array);

$placeholders will contain a sequence of ?, ?, ? placeholders, with the same number of ? as the size of the array. Then when you execute the statement, the array values are bound to the placeholders.

Solution 2:

I have personally done:

$in = substr(str_repeat('?,', count($array)), 0, -1);

$sql = "SELECT * FROM table WHERE field IN ($in)";

This will provide you with ?, for each array element and remove the trailing comma.

Post a Comment for "Mysql In Clause Parameterization In Php, Python"