简体   繁体   English

PHP PDO foreach问题

[英]PHP PDO foreach issue

So I have a php function that updates 2 columns in a database. 所以我有一个php函数,可以更新数据库中的2列。 It looks like this: 看起来像这样:

$fields = array("firstname" => "Joe", "lastname" = "Dunno");

$stmt = $connection->prepare("UPDATE users SET firstname = :firstname, lastname = :lastname WHERE user_id = :user_id");

foreach ($fields as $key => $value)
{
    $stmt->bindParam(":" . $key, $value);
} 

$stmt->bindParam(":user_id", $user_id);

However when i execute the statement for some reason it likes to update firstname and lastname both to Dunno instead of Joe and Dunno. 但是,当我出于某种原因执行该语句时,它喜欢将名字和姓氏都更新为Dunno,而不是Joe和Dunno。

I tried echo'ing the $key and $value and it prints out correctly. 我尝试回显$key$value ,它可以正确打印出来。

For some weird reason if i use this for loop it works correctly. 出于某些奇怪的原因,如果我使用此for循环,它将正常工作。

for ($fieldsKeys = array_keys($fields), $x = 0; $x < count($fields); $x++)
{
    $stmt->bindParam(":" . $fieldsKeys[$x], $fields[$fieldsKeys[$x]]);
}

bindParam binds to a variable, that's why both fields are set to the same value (the last value of $value ). bindParam绑定到一个变量,这就是为什么两个字段都设置为相同的值( $value的最后一个$value )的原因。 You should use bindValue instead: 您应该改为使用bindValue

$stmt->bindValue(":" . $key, $value);

In your code, PDO remembers that it needs to use $value variable for :firstname and :lastname . 在您的代码中,PDO记住它需要将$value变量用于:firstname:lastname At statement execution time the $value is Dunno , so both fields get this value. 在语句执行时, $valueDunno ,因此两个字段都获得该值。 If you use bindValue , PDO does not remember the variable that was used, but its value, and this is what you need. 如果使用bindValue ,则PDO不会记住使用的变量,而是它的值,这就是您所需要的。

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

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