我很想知道是否可以使用 PDO 将值数组绑定(bind)到占位符。这里的用例尝试传递一个值数组以与 IN()
条件一起使用。
我希望能够做这样的事情:
<?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 绑定(bind)并引用数组中的所有值。
目前我正在做的事情:
<?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();
?>
这当然可以完成这项工作,但只是想知道我是否缺少内置解决方案?
最佳答案
您必须构造查询字符串。
<?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();
?>
克里斯(评论)和someoneisintrouble都建议foreach循环......
(...)
// bindvalue is 1-indexed, so $k+1
foreach ($ids as $k => $id)
$stmt->bindValue(($k+1), $id);
$stmt->execute();
...可能是多余的,因此 foreach
循环和 $stmt->execute
可以替换为 ...
<?php
(...)
$stmt->execute($ids);
关于php - 我可以将数组绑定(bind)到 PDO 查询中的 IN() 条件吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24805794/