我可以数组绑定到一个IN()条件? [英] Can I bind an array to an IN() condition?

查看:239
本文介绍了我可以数组绑定到一个IN()条件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很好奇,想知道这是否是可能的值数组绑定到使用PDO的占位符。这里的用例试图传递值的数组与使用 IN()状态。结果
我不是在解释很好,所以这里的一些伪code证明。我希望能够做这样的事:

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'm not very good at explaining, so here's some psuedocode to demonstrate. 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?

推荐答案

我觉得soulmerge是正确的。你必须构造查询字符串。

i think soulmerge is right. 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();
?>

修正:丹,你是对的。固定code(虽然没有测试)

fix: dan, you were right. fixed the code (didn't test it though)

编辑:无论克里斯(评论)和somebodyisintrouble建议的foreach循环...

edit: 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-&GT;执行可能是由刚刚更换...

... might be redundant, so the foreach loop and the $stmt->execute could be replaced by just ...

<?php 
  (...)
  $stmt->execute($ids);
?>

(同样,我没有测试)

这篇关于我可以数组绑定到一个IN()条件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆