user6842332 user6842332 - 1 year ago 58
MySQL Question

Running update Query in while loop with associative array


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

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) {
string(6) "Peter"
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,


Rob Rob
Answer Source

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'";
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download