Monday, December 26, 2022

PHP & MySQL PDO: PDO binding values for MySQL IN statement - Bind an array to an IN() condition?

The answer there was that, for a variable sized list in the in clause, you'll need to construct the query yourself.
Consider your array like:
$values = array(1, 2, 3, 4, 5);

$count = count($values);

$criteria = sprintf("?%s", str_repeat(",?", ($count ? $count - 1 : 0)));

$sql = sprintf("DELETE FROM table where column NOT IN(%s)", $criteria);

$pdo->sth = prepare($sql);
$pdo->sth->execute($values);

SQL should be: DELETE FROM table where column IN (?,?,?,?,?)

No comments:

Post a Comment