Update MySQL table with an Array using Foreach

匿名 (未验证) 提交于 2019-12-03 09:14:57

问题:

This is driving me potty so please help.

I am trying to update a Mysql table with an array.

Something like this

$a = array('1', '2', '3');  foreach($a as $id){  mysql_query("UPDATE table SET id = '$id' WHERE column = 'something'") or die(mysql_error());  } 

So after the update the id column should have values 1, 2, 3 Instead it updates with 1, 1, 1

Not exactly what I want.

Can someone please showing what I am doing wrong.

Thanks in advance.

回答1:

Each of your update statements in the foreach are acting on the same row or set of rows each time. In your example, you use "where column = 'something'". If that doesn't change with each iteration of the foreach loop, you'll keep updating the same rows.



回答2:

Do you change your where-statement in the real code? Now you are overwriting every row where column = 'something' which would means every row would be updated every time and end up with the same content.

EDIT: Answering comment

Well, you would need a non-static WHERE-statement for this. You could do something like the edit in my post...

$a = array('1' => 'something1', '2' => 'something2', '3' => 'something3');  foreach($a as $id => $where){     mysql_query("UPDATE table SET id = '$id' WHERE column = '$where'") or die(mysql_error()); } 


回答3:

I don't see the 'where' condition changing in the loop. Each time you do "WHERE column = 'something'" it will match and replace ALL the rows, overwriting the ID from each previous update.

UPDATE:

Some of us wrote similar responses at the same time. I should have hit 'refresh' one more time before 'add'

For what it's worth, if this is a one-time fix to get sequential ids on a table, you can do that with straight mysql:

mysql> select * from foo; +------+------+ | id   | name | +------+------+ |    0 | aaa  | |    0 | bbb  | |    0 | ccc  | |    0 | ddd  | +------+------+ 4 rows in set (0.00 sec)  mysql> set @ct=0; Query OK, 0 rows affected (0.00 sec)  mysql> update foo set id=(@ct:=@ct+1); Query OK, 4 rows affected (0.00 sec) Rows matched: 4  Changed: 4  Warnings: 0  mysql> select * from foo; +------+------+ | id   | name | +------+------+ |    1 | aaa  | |    2 | bbb  | |    3 | ccc  | |    4 | ddd  | +------+------+ 4 rows in set (0.00 sec) 

Use an 'order by' if you like, for instance:

mysql> update foo set id=(@ct:=@ct+1) order by name 


易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!