使用Foreach使用Array更新MySQL表

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.

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

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

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.