PDO 将参数与数组绑定
我正在尝试在 PHP 中创建一个方法,它将动态地将参数绑定到 PDO 查询语句。不幸的是,在我下面的代码中,我只能绑定 1 个参数,因为添加更多参数将覆盖以前的参数。然而,有没有好的方法来解决这个问题呢?
我希望有人能提供帮助。谢谢!
function executeQuery($query, $critArr = null) {
$rows = array();
try {
$stmt=$this->pdo->prepare($query);
if (!empty($critArr)) {
foreach($critArr as $cKey=>$cValue) {
$stmt->bindParam($cKey, $cValue); //!!
}
}
$stmt->execute();
I am trying to create a method in PHP, that will dynamically bind parameters to a PDO query statement. Unfortunately, in my code below, i can only bind 1 parameter, because adding more parameters will override the previous parameters. Nevertheless, is there a good way to fix this problem?
I hope someone can help. Thanks!
function executeQuery($query, $critArr = null) {
$rows = array();
try {
$stmt=$this->pdo->prepare($query);
if (!empty($critArr)) {
foreach($critArr as $cKey=>$cValue) {
$stmt->bindParam($cKey, $cValue); //!!
}
}
$stmt->execute();
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
你不需要这样做。
execute
方法已经接受一组参数:最初的问题是
bindParam
通过引用工作,而foreach
只是一遍又一遍地重用相同的变量,而不是在循环底部销毁它们并在顶部(重新)创建它们。您实际上是一遍又一遍地重新绑定相同的变量。 (顺便说一下,这与mysqli
扩展存在同样的问题,但它也缺少方便的已经获取数组execute
方法。)You don't need to do that. The
execute
method already takes an array of parameters:The original problem is that
bindParam
works by reference, andforeach
simply reuses the same variables over and over rather than destroy them at the bottom of the loop and (re)create them at the top. You were effectively re-binding the same variable over and over. (Incidentally, this is the same problem that themysqli
extension has, while it also lacks the convenient already-takes-an-arrayexecute
method.)通过引用 &$cValue 传递 foreach $cValue,您的函数得到了改进。这应该可以解决你的问题。
Your function improved with passing foreach $cValue by reference &$cValue. This should solve your problem.