PDO bindParam在foreach中不起作用 [英] PDO bindParam not working in foreach

查看:49
本文介绍了PDO bindParam在foreach中不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为应用程序使用PDO,但是PDO bindParam()遇到了问题.我有一个数组,我想使用for循环或foreach()PDO bindParam()使用array的值,但foreach()却得到了意外的结果.当我在for循环中使用bindParam()时,它工作正常.我尝试过的是

I am using PDO for an application but getting a problem for PDO bindParam(). I have an array and I want to use the values of array for PDO bindParam() using for loop or foreach() but an unexpected result is getting by foreach(). When I used bindParam() in for loop, it worked fine. What I tried was

$con = $this->connection();
$stmt = $con->prepare($sql);

for($i = 0; $i < count($params); $i++){
   $stmt->bindParam($i + 1, $params[$i], PDO::PARAM_STR, 10);
}
$stmt->execute();
$result = $stmt->fetchAll();//$result is OK

但是当我在foreach()中使用bindParam()时,结果是空的array().代码下方

But when I used bindParam() in foreach() then I got an empty array() as result. Below the codes

$con = $this->connection();
$stmt = $con->prepare($sql);

foreach($params as $key=>$val){ //Here
    $stmt->bindParam($key + 1, $val, PDO::PARAM_STR, 10);
}
$stmt->execute();
$result = $stmt->fetchAll(); //$result is an empty array

我想知道为什么会这样.我找不到原因.任何信息将不胜感激.

I'm wondering why this happened. I can't find out the reason. Any information will be appreciated.

我改用bindValue()解决了我的问题.

EDIT : I solved my problem using bindValue() instead.

推荐答案

使用bindValue()而不是bindParam(). bindParam()绑定到引用,因此在执行查询时,所有参数都使用$val的最后一个值.

use bindValue() instead of bindParam(). bindParam() binds to a reference, so when you execute the query all the parameters use the last value of $val.

这篇关于PDO bindParam在foreach中不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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