PDO excels in executing statements with IN clauses when using arrays for their values, as illustrated in the following code:
$in_array = [1, 2, 3]; $in_values = implode(',', $in_array); $my_result = $wbdb->prepare("SELECT * FROM my_table WHERE my_value IN (?)"); $my_result->execute([$in_values]); $my_results = $my_result->fetchAll();
However, the following code exhibits unexpected behavior:
$in_array = [1, 2, 3]; $in_values = implode(',', $in_array); $my_result = $wbdb->prepare("SELECT * FROM my_table WHERE my_value IN (:in_values)"); $my_result->execute([':in_values' => $in_values]); $my_results = $my_result->fetchAll();
Instead of returning all items whose my_value matches values in $in_array, this code only returns the item whose my_value matches the first item in $in_array.
PDO is not equipped to handle such scenarios effectively. To use arrays in IN clauses, we must dynamically generate a string with placeholders and insert it into the query. With positional placeholders, the solution is as follows:
$in = str_repeat('?,', count($in_array) - 1) . '?'; $sql = "SELECT * FROM my_table WHERE my_value IN ($in)"; $stm = $db->prepare($sql); $stm->execute($in_array); $data = $stm->fetchAll();
For cases with multiple placeholders, consider leveraging array_merge(). For instance:
$arr = [1, 2, 3]; $in = str_repeat('?,', count($arr) - 1) . '?'; $sql = "SELECT * FROM table WHERE foo=? AND column IN ($in) AND bar=? AND baz=?"; $stm = $db->prepare($sql); $params = array_merge([$foo], $arr, [$bar, $baz]); $stm->execute($params); $data = $stm->fetchAll();
In scenarios with named placeholders, the process is more intricate, as it involves generating a sequence of placeholders, for example, :id0, :id1, :id2.
$ids = [1, 2, 3]; $in = ""; $i = 0; foreach ($ids as $item) { $key = ":id" . $i++; $in .= ($in ? "," : "") . $key; $in_params[$key] = $item; } $sql = "SELECT * FROM table WHERE id IN ($in)"; $stm = $db->prepare($sql); $stm->execute(array_merge($params, $in_params)); $data = $stm->fetchAll();
Fortunately, named placeholders do not necessitate strict order, allowing for merging of arrays in any sequence.
The above is the detailed content of How Can I Effectively Use PDO's IN Clause with Arrays in PHP?. For more information, please follow other related articles on the PHP Chinese website!