-1

i am fetching different record from the database but using single quantity field trying to insert multiple records into MYSQL but every time for loop or any other loop overriding single value in all rows(inserting single first value in every field), badly stuck. kindly suggest what kind of appropriate steps should be done.

<input type="text" name="qty[]" id="qtyid" style="width:40px;">

<?php   
if(isset($_POST["update"])) {
  $usersCount=count($_POST['qty']);

  $qtys=implode(",",$_POST['qty']);
  for($i=0;$i<$usersCount;$i++) {
    $query="UPDATE cart set qty='".$qtys."' WHERE prodid='$cartid'";
    $dbh->query($query);
    echo $qtys; 
  }
}
$total=$total*$qtys;
?>

database tuple image

Cjmarkham
  • 9,484
  • 5
  • 48
  • 81

1 Answers1

0

Your "question" is unclear. I read it couple times nad i still dont know what is your problem.

Anyway. I'll try to explain what your code do in case it would help you to understand where the problem is.

//if form was submited and input of name "update" was in
if(isset($_POST["update"])) {

  // count array created by inputs of name="qty[]"
  $usersCount=count($_POST['qty']);

  // make a string from that array, separating the keys by a "," char
  $qtys=implode(",",$_POST['qty']);

  // loop as many times as number of elements in that array = <input name="qty[]"> you had in submited form
  for($i=0;$i<$usersCount;$i++) {

    // and finally, do always the same for each loop repeat
    $query="UPDATE cart set qty='".$qtys."' WHERE prodid='$cartid'";
    $dbh->query($query);
    echo $qtys; 
  }
}

So in conclusion your loop is doing always the same - every each repeat:

`$query="UPDATE cart set qty='".$qtys."' WHERE prodid='$cartid'";`

Basically to do that you would't need to have loop. Because in that query you change value of column qty wherever column prodid is equal to something

RysQ
  • 347
  • 3
  • 14
  • thanks rysQ. I am simply trying to insert multiple quantities where prodid=$cartid(product id let say 2 and 4). For example user entered 15 quanities for product id no 2 and 20 for product id no 4 But what is happening query insert and repeat 15 first inserted value in both rows where product id 2 and 4 instead of both values explicitly when i debugging the values by print it shows different values. It might be clear now. – Salman Ahmad Jan 10 '16 at 09:27
  • Hmm. Values might be different but I cant find where you change value of `$cartid` in your `for` . It looks '$cartid` stays always the same for each repeat of loop. So code will only `UPDATE` rows where (for example) `prodid = 2`. You need to change `$cartid` in your loop for different `prodid` rows. Also this might be helpful: [link](http://stackoverflow.com/questions/3432/multiple-updates-in-mysql) – RysQ Jan 10 '16 at 14:03