[英]How do I update each row in a column to each array value, instead of each row updating to the last array value?
How do I update each row in the column to each array value, instead of each row updating to the last array value?如何将列中的每一行更新为每个数组值,而不是将每一行更新为最后一个数组值?
foreach ($array as $i => $value) {
$sql = "UPDATE table SET column_1='$value' WHERE column_2='value2'";
mysqli_query($connDB, $sql);
}
Input:输入:
123
123
456456
789789
$array: $数组:
[0] => 123
[1] => 456
[2] => 789
Current result:当前结果:
column_1![]() |
column_2 ![]() |
---|---|
789 ![]() |
value2![]() |
789 ![]() |
value2![]() |
789 ![]() |
value2![]() |
What I want:我想要的是:
column_1![]() |
column_2 ![]() |
---|---|
123 ![]() |
value2![]() |
456 ![]() |
value2![]() |
789 ![]() |
value2![]() |
You set $value1 in the query, change it to $value:您在查询中设置 $value1,将其更改为 $value:
$sql = "UPDATE table SET column_1='$value' WHERE column_2='value2'";
the problem is column_2 is not unique for each row.问题是 column_2 对于每一行都不是唯一的。 you must have unique value like id in a table for proper updating or deleting so you can select id of all rows with condition column_2=value2 and then update each row using its unique id
您必须在表中具有唯一值(如 id)才能正确更新或删除,以便您可以使用条件 column_2=value2 对所有行的 select id 进行更新,然后使用其唯一 id 更新每一行
My solution was to create a third column to determine the status of the whole row.我的解决方案是创建第三列来确定整行的状态。 Then, during each loop, the status would update with a limit of 1 row at a time.
然后,在每个循环期间,状态将更新,一次限制为 1 行。 Only rows with 'updating' status can be changed.
只能更改具有“更新”状态的行。 ('locked' is the status column default)
('locked' 是状态栏的默认值)
foreach ($array as $i => $value) {
$status_update = "UPDATE table SET status='updating' WHERE column_2='value_2' AND status='locked' LIMIT 1";
mysqli_query($connDB,$status_update);
$value_update = "UPDATE table SET column_1='$value' WHERE status='updating'";
mysqli_query($connDB, $value_update);
$status_ready = "UPDATE table SET status='ready' WHERE column_2='value_2' AND status='updating'";
mysqli_query($connDB, $status_ready);
}
Results:结果:
column_1![]() |
column_2 ![]() |
status![]() |
---|---|---|
123 ![]() |
value_2![]() |
ready![]() |
456 ![]() |
value_2![]() |
ready![]() |
789 ![]() |
value_2![]() |
ready![]() |
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.