user6842332 user6842332 - 1 month ago 8
MySQL Question

Running update Query in while loop with associative array

My

$updatearray
contains various data (
$_POST
data) and needs to update a row in a table in my MySQL database.

$updatearray
is a associative array. where $key is the column name and $value is the value that needs to overwrite the old data.

for example:

array(2) {
["firstname"]=>
string(6) "Peter"
["lastname"]=>
string(6) "Griffin"
}


Now I'm looking for a way to update my DataBase. I tried to following :

foreach ($updatearray as $key => $value){
$edit = $db->query("UPDATE 'users' SET $key='$value' WHERE userid='1'");

if (!$edit) {
die('Invalid query: ' . mysqli_error());
}
}


I don't know if there's a better way to solve this problem. And if this problem is solvable in my way at all. But that's why I'm here.

Thanks in advance,

Mike

Rob Rob
Answer

You are doing it the right way, the only wrong thing is that you have an error in your SQL syntax.

Don't put your tablename in quotes.

"UPDATE users SET $key='$value' WHERE userid='1'";