Resantic
Resantic

Reputation: 57

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]]);
}

Upvotes: 1

Views: 33

Answers (1)

Yury Fedorov
Yury Fedorov

Reputation: 14938

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.

Upvotes: 4

Related Questions