简体   繁体   English

PHP数组更新多个Mysql行

[英]PHP array updating multiple Mysql rows

I've a problem when updating multiple Mysql rows when using an array, Lets start with the following submit form : 使用数组更新多个Mysql行时出现问题,让我们从以下提交表单开始:

$n = array();  //Supplier Name
$s = array();  //Short Name
$o = array();  //Shipment No.
$id = array(); //Supplier ID

<form action="editing_supplier.php" method="post">
<input type="hidden" value="<?php echo $row['id'] ?>" name="id[]">
<input type="text" value="<?php echo $row['name']?>" required name="n[]">
<input type="text" value="<?php echo $row['short_name']?>" required  name="s[]">
<input type="text" value="<?php echo $row['shipment_no']?>" required  name="o[]">
<input type="submit" value="Confirm Editing" >
</form>

Now when clicking Submit, which directly opens up "editing_supplier.php" page- The following codes are bellow : 现在,当单击“提交”时,将直接打开“ editing_supplier.php”页面-以下代码如下:

if((isset($_POST['n'])) && (isset($_POST['s'])) && (isset($_POST['o']))){

//Shows up the ID for each Supplier Name
if(is_array($_POST['id'])) {
foreach($_POST['id'] as $id){

//Updates Supplier Name
if(is_array($_POST['n'])) {
foreach($_POST['n'] as $value){
$query = "UPDATE suppliers SET name = '".$value."' where id ='".$id."'";
$result = mysql_query($query);
}
}


//Updates Short_Name
if(is_array($_POST['s'])) {
foreach($_POST['s'] as $value1){
$query = "UPDATE suppliers SET short_name = '".$value1."' where id ='".$id."'";
$result = mysql_query($query);
}
}

//Updates Shipment No.
if(is_array($_POST['o'])) {
foreach($_POST['o'] as $value2){
$query = "UPDATE suppliers SET shipment_no = '".$value2."' where id ='".$id."'";
$result = mysql_query($query);
}
}


//End of for Each id
}
}

What actually Does, When Selecting a single row to update..It works perfectly ! 当选择单行进行更新时,实际执行的操作是完美的! But when doing a multiple selection in-order to make an update for them, it messes up all the values..As if copying the last id,supplier name, short name and shipment no. 但是,当为了对其进行更新而进行多项选择时,它会弄乱所有值。好像复制了最后一个ID,供应商名称,简称和发货编号。 to all the selected rows. 到所有选定的行。

I think this is due to the series of foreach within the foreach($id). 我认为这是由于foreach($ id)中的一系列foreach。 I would write : 我会写:

foreach($_POST['id'] as $index=>$id) {

to keep track of the index of your record, and then do not do any other foreach but rather : 跟踪记录的索引,然后不执行其他任何foreach操作,而是:

$query = "UPDATE suppliers SET name = '".$_POST['n'][$index]."' where id ='".$id."'";

so you keep the link between the $id value and the other variables. 因此,您可以保留$ id值与其他变量之间的链接。

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

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