php - 我可以将数组绑定(bind)到 PDO 查询中的 IN() 条件吗?

标签 php arrays pdo prepared-statement where-in

我很想知道是否可以使用 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();
?>

chris(评论)和 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/8957736/

相关文章:

php - fatal error : Class 'PHPMailer' not found

python - Matplotlib:切片 plt.imshow() 是否对应于切片源 numpy 数组?

Java、switch case 和数组

PHP PDO 准备语句绑定(bind) NULL 值

php - 如何使用 PHP 显示文件系统中的图像

php - 突然密码列抛出: SQLSTATE[42S22]: Column not found

php - 当 X 列的值为 ACCEPTED 时,为特定的 div 着色

php - 通过 PHP 检测 MySQL InnoDB

php - 事件的随机加权选择

c - C 中的合并排序不起作用