带有 PDO 的 WHERE IN 子句的绑定参数 [英] Binding parameters for WHERE IN clause with PDO

查看:34
本文介绍了带有 PDO 的 WHERE IN 子句的绑定参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的代码:

$myArray = implode($myArray, ',');
$sth = $dbh->prepare('SELECT foo FROM bar WHERE ids IN (:ids)');
$sth->bindParam(':ids', $myArray);
$sth->execute();
$result = $sth->fetch();
echo $sth->rowCount();

始终显示计数为 1,但是当我跳过参数化并仅将变量本身添加到它的位置时,我得到了准确的计数.这是怎么回事?

Always shows a count of 1, but when I skip the parametrization and just add the variable itself in it's place, I get an accurate count. What's going on here?

推荐答案

您不能像那样为 IN 子句绑定参数.$myArray 字符串只会算作一个值,就像你这样做一样:

You can't bind a parameter for the IN clause like that. The $myArray string will only count as one value, like if you did this:

SELECT foo FROM bar WHERE ids IN ('1,2,3')

即使有三个逗号分隔的值,数据库也只将它们作为一个字符串值读取.

Even though there are three comma delimited values, the database reads them as only one string value.

您需要手动将 IN 列表插入到查询中,这是老派的方式.

You need to manually insert the IN list into the query, the old-school way.

'SELECT foo FROM bar WHERE ids IN (' . $myArray .')'

不幸的是,没有其他办法.至少现在是这样.

There is unfortunately no other way. At least for now.

这篇关于带有 PDO 的 WHERE IN 子句的绑定参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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