简体   繁体   English

PDO bindParam在foreach中不起作用

[英]PDO bindParam not working in foreach

I am using PDO for an application but getting a problem for PDO bindParam() . 我正在使用PDO作为应用程序但是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() . 我有一个数组和我想使用数组的值PDO bindParam()使用for循环或foreach()但意外的结果是通过得到foreach() When I used bindParam() in for loop, it worked fine. 当我在for循环中使用bindParam()时,它运行正常。 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

But when I used bindParam() in foreach() then I got an empty array() as result. 但是当我在foreach()使用bindParam() ,我得到一个空array()作为结果。 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. 任何信息将不胜感激。

EDIT : I solved my problem using bindValue() instead. 编辑:我使用bindValue()解决了我的问题。

use bindValue() instead of bindParam() . 使用bindValue()而不是bindParam() bindParam() binds to a reference, so when you execute the query all the parameters use the last value of $val . bindParam()绑定到引用,因此当您执行查询时,所有参数都使用$val的最后一个值。

If you already have the items in an array, there's no reason to call $stmt->bindParam in a loop; 如果已经有数组中的项,则没有理由在循环中调用$stmt->bindParam ; just do: 做就是了:

$con = $this->connection();
$stmt = $con->prepare($sql);
$stmt->execute($params);
$result = $stmt->fetchAll();

Per the PHP documentation : 根据PHP文档

Execute the prepared statement. 执行准备好的声明。 If the prepared statement included parameter markers, you must either: 如果准备好的语句包含参数标记,则必须:

call PDOStatement::bindParam() to bind PHP variables to the parameter markers: bound variables pass their value as input and receive the output value, if any, of their associated parameter markers 调用PDOStatement :: bindParam()将PHP变量绑定到参数标记:绑定变量将其值作为输入传递,并接收其相关参数标记的输出值(如果有)

or pass an array of input-only parameter values 或传递一组仅输入参数值

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM