PHP - Using PDO with IN clause array -
i'm using pdo execute statement in
clause uses array it's values:
$in_array = array(1, 2, 3); $in_values = implode(',', $in_array); $my_result = $wbdb->prepare("select * my_table my_value in (".$in_values.")"); $my_result->execute(); $my_results = $my_result->fetchall();
above code works fine, question why doesn't:
$in_array = array(1, 2, 3); $in_values = implode(',', $in_array); $my_result = $wbdb->prepare("select * my_table my_value in (:in_values)"); $my_result->execute(array(':in_values' => $in_values)); $my_results = $my_result->fetchall();
this code return item who's my_value
equals first item in $in_array
(1), not remaining items in array (2, , 3).
pdo not such things. need create string question marks dynamically , insert query.
$in = str_repeat('?,', count($in_array) - 1) . '?'; $sql = "select * my_table my_value in ($in)"; $stm = $db->prepare($sql); $stm->execute($in_array); $data = $stm->fetchall();
in case there other placeholders in query, use following approach (the code taken pdo tutorial):
you use array_merge()
function join variables single array, adding other variables in form of arrays, in order appear in query:
$arr = [1,2,3]; $in = str_repeat('?,', count($arr) - 1) . '?'; $sql = "select * table foo=? , column in ($in) , bar=? , baz=?"; $stm = $db->prepare($sql); $params = array_merge([$foo], $arr, [$bar, $baz]); $stm->execute($params); $data = $stm->fetchall();
in case using named placeholders, code little more complex, have create sequence of named placeholders, e.g. :id0,:id1,:id2
. code be:
// other parameters going query $params = ["foo" => "foo", "bar" => "bar"]; $ids = [1,2,3]; $in = ""; foreach ($ids $i => $item) { $key = ":id".$i; $in .= "$key,"; $in_params[$key] = $item; // collecting values key-value array } $in = rtrim($in,","); // :id0,:id1,:id2 $sql = "select * table foo=:foo , id in ($in) , bar=:bar"; $stm = $db->prepare($sql); $stm->execute(array_merge($params,$in_params)); // merge 2 arrays $data = $stm->fetchall();
luckily, named placeholders don't have follow strict order, can merge our arrays in order.
Comments
Post a Comment