Home >Backend Development >PHP Tutorial >How Can I Bind an Array to an IN() Clause in a PDO Query?
Can Array Values be Bound to an IN() Condition in a PDO Query?
Binding an array of values to an IN() condition using PDO is possible, but it requires manual placeholder construction. Here's how:
Here's an example:
$ids = [1, 2, 3, 7, 8, 9]; $inQuery = str_repeat('?,', count($ids) - 1) . '?'; // ?,?,?,?,?,? $stmt = $db->prepare("SELECT * FROM table WHERE id IN($inQuery)"); $stmt->execute($ids);
In case of named placeholders:
Here's an example:
$ids = [1, 2, 3]; $in = ""; $i = 0; // external counter foreach ($ids as $item) { $key = ":id" . $i++; $in .= ($in ? "," : "") . $key; // :id0,:id1,:id2 $in_params[$key] = $item; // collect values } $sql = "SELECT * FROM table WHERE id IN ($in)"; $stmt = $db->prepare($sql); $stmt->execute(array_merge(["foo" => "foo", "bar" => "bar"], $in_params));
The above is the detailed content of How Can I Bind an Array to an IN() Clause in a PDO Query?. For more information, please follow other related articles on the PHP Chinese website!