如果在phpmyadmin中输入,则以下查询将返回所有想要的结果:
SELECT postid, voting
FROM postvotes
WHERE userid = 1
AND postid IN
(1007,1011,1012,1013,1014,
1015,1016,1017,1018,1019,1020,1021,1023,1025,1026,
1027,1028,1029,1030,1031)
但PDO无法fetchAll() . 它只返回第一个匹配,如fetch() .
怎么了?
PHP代码:
private function userPostVotings( $postIDs ) {
// $postIDs contains a string like 1,2,3,4,5,6,7...
// generated through implode(',', idArray)
try {
$userPostVote = $this->_db->prepare('SELECT postid, voting
FROM postvotes
WHERE userid = ?
AND postid IN ( ? )');
$userPostVote->setFetchMode(\PDO::FETCH_ASSOC);
$userPostVote->execute( array( $this->_requester['id'], $postIDs ) );
while ( $res = $userPostVote->fetch() ) {
var_dump( $res );
}
} catch (\PDOException $p) {}
}
如果我回显出此方法中使用的查询并通过phpmyadmin触发它,我会得到正确数量的结果 . 然而,PDO只给出了第一个 . 无论是带有fetch()还是fetchAll()的循环 .
2 回答
它当然不是PDO的fetchAll(),而是你的查询 .
哪个不是
但
当然它只会找到第一个值,因为这个字符串将被转换为第一个数字
必须创建一个包含表示每个数组成员的占位符的查询,然后绑定此数组值以便执行:
为了使这个查询更灵活,最好动态创建一个带有?的字符串:
您无法在PDO中的预准备语句中绑定数组 .
参考:Can I bind an array to an IN() condition?