PDO IN()数组语句和一个占位符 [英] PDO IN() Array Statement AND a placeholder
问题描述
我在SO上找到了这段代码,非常适合同时使用PDO和IN()语句.
I found this code on SO, which is great for using PDO and the IN() statement together.
$values = explode(',', $values) ; # 1,4,7
$placeholders = rtrim(str_repeat('?, ', count($values)), ', ') ;
$query = "SELECT * FROM table WHERE id IN ($placeholders)";
$stm = $db->prepare($query) ;
$stm->execute($values) ;
但是,如何在查询中添加其他内容,使查询看起来像这样:
However, how can I mix in another addition to the query so the query looks like this:
$query = "SELECT * FROM table WHERE id IN ($placeholders) AND product=?";
$stm = $db->prepare($query) ;
$stm->execute(array($values,$product)) ; //error happens when adding product placeholder
我以为这样可以,但是我得到了:
I thought this would work but I get:
警告::PDOStatement :: execute()[pdostatement.execute]:SQLSTATE [HY093]:无效的参数编号:绑定变量的数量与第3行中标记的数量不匹配($ stm行)
Warning: PDOStatement::execute() [pdostatement.execute]: SQLSTATE[HY093]: Invalid parameter number: number of bound variables does not match number of tokens in line 3 (the $stm line)
有什么主意如何使其表现出预期的效果吗?
Any idea how to get this to behave as intended?
已更新执行到数组,但仍无法正常工作.
UPDATED execute to array, still not working..
推荐答案
解决方案
如果$values
是数组,这应该起作用:
Solution
This should work, if $values
is an array:
$query = "SELECT * FROM table WHERE id IN ($placeholders) AND product=?";
$stm->execute(array_merge($values, array($product)));
说明
execute()
期望提供一个参数-在这种情况下为数组.通过添加array_merge($values, array($product))
,您将创建一个在最后添加$product
的数组,因此查询应该可以正常工作.
Explanation
execute()
expects one parameter - in this case an array - to be provided. By adding array_merge($values, array($product))
you create one array with $product
added at the end, so the query should work correctly.
在此处查看演示: http://ideone.com/RcClX
这篇关于PDO IN()数组语句和一个占位符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!