简体   繁体   English

循环更新sql中的多行

[英]updating multiple rows in sql in a loop

i have multiple input-fields with the same name as id's and the other fields with other names like 我有多个输入字段,其名称与id相同,其他字段的名称与其他类似

<input name="id[]" value="1" />  <input name="st[]" value="4" />

<input name="id[]" value="5" />  <input name="st[]" value="57" />

<input name="id[]" value="79" /> <input name="st[]" value="43" />
                             .
                             .    
                             .

in my sql table i want to change ...maybe id->3 and id->87 or whatever 10 others to update the column " st " with the value from the right side input field. 在我的sql表中,我想更改...也许是id-> 3和id-> 87或其他10个对象,以使用右侧输入字段中的值更新“ st ”列。 The key values from id and st are the same. id和st的键值相同。 I know the update-sql-syntax of one row. 我知道一行的update-sql-syntax。 but, if i want more rows i dont know what to do 但是,如果我想要更多的行,我不知道该怎么办

my reasoning was do it with Jquery Ajax or php Implode like 我的推理是用Jquery Ajax或php Implode做到的

$id = implode(',', $_POST['id']);
$st = implode(',', $_POST['st']);
$sql = "UPDATE table SET st=('$st') WHERE id=('$id')";

then i found this from user peterm 然后我从用户peterm找到了

   UPDATE table
   SET st = CASE id 
                      WHEN 'id_x' THEN 'st_x' 
                      WHEN 'id_y' THEN 'st_y'
                        ... 
                      ELSE st
                      END
 WHERE id IN('id_x', 'id_y', ...);

How do i get it with spontaneously entrys from my website-user in a loop (foreach?) 如何以循环方式从我的网站用户自发地获取条目(foreach?)

I hope it can resolve your problem. 我希望它可以解决您的问题。 You can use the code as below : 您可以使用以下代码:

if(!isset($_POST['id'] || count($_POST['id']) == 0){
    return;
}

foreach($_POST['id'] as $key => $id)){
    $sql = "UPDATE table SET st='{$_POST['st'][$key]}' WHERE id='{$id}'";
}
$SizeOfID=sizeof($id);

for($i=0;$i<$SizeOfID;$i++)
{
   $IDvalue=$id[$i];
   $STvalue=$st[$i];

   mysql_query("UPDATE table SET st='$STvalue' WHERE id='$IDvalue'");
}

There is also another quicker way to accomplish it without executing multiple sql because of the loop. 由于循环,还有另一种更快的方法可以完成它而无需执行多个sql。

But you must make sure that the query will be constructed in a way that it will "hit" on existing unique key ( for example the primary ) and so it will use the sql's ON DUPLICATE KEY to update its VALUES... 但是您必须确保查询的构建方式将使其“命中”现有的唯一键(例如主键),因此它将使用sql的ON DUPLICATE KEY更新其值。

For example: 例如:

<?php

$values = [];

foreach( $data as $id => $value ){

    $values[] = "( '".$id."', '".$value."' )";

}

if( (bool)$values ){

   $sql = "INSERT INTO table ( id, st ) VALUES".implode(',',$values)." ON DUPLICATE KEY UPDATE st = VALUES(st)";

   //execute $sql here

}

Of course you need to validate - sanitize data... the usual stuff... 当然,您需要验证-清理数据...常用的东西...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM