PHP PDO bindParam 陷入了 foreach

2021-12-26 00:00:00 php pdo

我有一个这样的循环:

foreach($Fields as $Name => $Value){$Query->bindParam(':'.$Name, $Value, PDO::PARAM_STR);}

没什么复杂的.但是,每个值都设置为数组中的最后一个 ($Fields).

我该如何解决?

解决方案

然而,感谢这个 伙计们.我发现您需要在之前使用 & 通过引用传递值:

foreach($Fields as $Name => &$Value){$Query->bindParam(':'.$Name, $Value, PDO::PARAM_STR);}

这让我发疯了.

来自 PHP.net 的实际报价:

<块引用>

Vili 2010 年 5 月 28 日 12:01

这有效(参考 $val):

 &$val){$sth->bindParam($key, $val);}?>

<块引用>

这会失败($val by value,因为bindParam需要&$variable):

 $val) {$sth->bindParam($key, $val);}?>

I had a loop like that :

foreach($Fields as $Name => $Value){
    $Query->bindParam(':'.$Name, $Value, PDO::PARAM_STR);
}

Nothing complicated. However, each value was set to the last one in the array ($Fields).

How can I fix that ?

解决方案

However, thanks to this guys. I found out that you need to pass the value by reference with a & before like that :

foreach($Fields as $Name => &$Value){
    $Query->bindParam(':'.$Name, $Value, PDO::PARAM_STR);
}

This was driving me nuts.

Actual quote from PHP.net :

Vili 28-May-2010 12:01

This works ($val by reference):

<?php
foreach ($params as $key => &$val){
    $sth->bindParam($key, $val);
}
?>

This will fail ($val by value, because bindParam needs &$variable):

<?php
foreach ($params as $key => $val) {
    $sth->bindParam($key, $val);
}
?>

相关文章