0

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.

1
  • @Voitcus If shorten the code, there is a for loop function. Commented Jun 4, 2013 at 12:40

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.