我可以将数组绑定到 IN() 条件吗? [英] Can I bind an array to an IN() condition?
问题描述
我很想知道是否可以使用 PDO 将一组值绑定到占位符.这里的用例是尝试传递一组用于 IN()
条件的值.
I'm curious to know if it's possible to bind an array of values to a placeholder using PDO. The use case here is attempting to pass an array of values for use with an IN()
condition.
我希望能够做这样的事情:
I'd like to be able to do something like this:
<?php
$ids=array(1,2,3,7,8,9);
$db = new PDO(...);
$stmt = $db->prepare(
'SELECT *
FROM table
WHERE id IN(:an_array)'
);
$stmt->bindParam('an_array',$ids);
$stmt->execute();
?>
并让 PDO 绑定并引用数组中的所有值.
And have PDO bind and quote all the values in the array.
目前我正在做:
<?php
$ids = array(1,2,3,7,8,9);
$db = new PDO(...);
foreach($ids as &$val)
$val=$db->quote($val); //iterate through array and quote
$in = implode(',',$ids); //create comma separated list
$stmt = $db->prepare(
'SELECT *
FROM table
WHERE id IN('.$in.')'
);
$stmt->execute();
?>
这当然可以完成工作,但只是想知道是否有我缺少的内置解决方案?
Which certainly does the job, but just wondering if there's a built in solution I'm missing?
推荐答案
您必须构造查询字符串.
You'll have to construct the query-string.
<?php
$ids = array(1, 2, 3, 7, 8, 9);
$inQuery = implode(',', array_fill(0, count($ids), '?'));
$db = new PDO(...);
$stmt = $db->prepare(
'SELECT *
FROM table
WHERE id IN(' . $inQuery . ')'
);
// bindvalue is 1-indexed, so $k+1
foreach ($ids as $k => $id)
$stmt->bindValue(($k+1), $id);
$stmt->execute();
?>
Chris(评论)和someoneisintroble 都建议foreach 循环......
Both chris (comments) and somebodyisintrouble suggested that the foreach-loop ...
(...)
// bindvalue is 1-indexed, so $k+1
foreach ($ids as $k => $id)
$stmt->bindValue(($k+1), $id);
$stmt->execute();
... 可能是多余的,所以 foreach
循环和 $stmt->execute
可以只替换为 ...
... might be redundant, so the foreach
loop and the $stmt->execute
could be replaced by just ...
<?php
(...)
$stmt->execute($ids);
这篇关于我可以将数组绑定到 IN() 条件吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!