Stack Overflow is a community of 4.7 million programmers, just like you, helping each other.

Join them; it only takes a minute:

Sign up
Join the Stack Overflow community to:
  1. Ask programming questions
  2. Answer and help your peers
  3. Get recognized for your expertise

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.

share|improve this question
    
@Voitcus If shorten the code, there is a for loop function. – Ali Hamra Jun 4 '13 at 12:40

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.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.