简体   繁体   中英

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 :

$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 :

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. to all the selected rows.

I think this is due to the series of foreach within the foreach($id). 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 :

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

so you keep the link between the $id value and the other variables.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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