PHP's PDO (PHP Data Objects) provides a mechanism for binding placeholders in queries to values in an array. However, it doesn't natively support binding an array of values to an IN() condition.
As a workaround, you can manually construct a placeholder string by iterating over the array and concatenating placeholders with commas.
$ids = [1, 2, 3, 7, 8, 9]; $in = str_repeat('?,', count($ids) - 1) . '?';
The $in variable will contain a string like "?,?,?,?,?,?".
Prepare the query using the placeholder string:
$stmt = $db->prepare("SELECT * FROM table WHERE id IN($in)");
Execute the query and pass the array as arguments:
$stmt->execute($ids);
For named placeholders, such as :id0, :id1, :id2, etc., you'll need to manually create a sequence of placeholders and collect values into an associative array.
$i = 0; $in_params = []; foreach ($ids as $item) { $key = ":id" . $i++; $in_params[$key] = $item; $in .= ($in ? ',' : '') . $key; }
While PDO doesn't explicitly allow binding an array to an IN() condition, you can replicate the functionality by manually constructing a placeholder string or using named placeholders with an associative array. These approaches provide a convenient way to handle arrays in IN() conditions within PDO queries.
The above is the detailed content of How Can I Bind an Array to an IN() Clause in PDO?. For more information, please follow other related articles on the PHP Chinese website!