简体   繁体   中英

PHP PDO foreach issue

So I have a php function that updates 2 columns in a database. 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.

I tried echo'ing the $key and $value and it prints out correctly.

For some weird reason if i use this for loop it works correctly.

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 ). You should use bindValue instead:

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

In your code, PDO remembers that it needs to use $value variable for :firstname and :lastname . At statement execution time the $value is Dunno , so both fields get this value. If you use bindValue , PDO does not remember the variable that was used, but its value, and this is what you need.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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