简体   繁体   中英

How do i properly loop and update quantities in a database.

Hello I am currently having problems updating my database quantities with a for loop. Right now i created a shopping cart and when the user purchases a item i want update the quantities in my database. The problem is i can only insert the last product id in the shopping so only 1 of the items update even though i have it in a loop. The code is long so im only going to show the part that i am having trouble with.

  for($i=0; $i<count($cart); $i++){
   $s += $cart[$i]->price * $cart[$i]->quantity;
   $tax= $s*.05;
   $shipping=$s* .02;
  $total=$s+$tax+$shipping;
   ?>
 <tr>
    <td><?php echo $cart[$i]->id; ?></td>
    <td><?php echo $cart[$i]->name; ?></td>
    <td><?php echo $cart[$i]->price; ?></td>
    <td><?php echo $cart[$i]->quantity; ?></td>
    <td><?php echo $cart[$i]->price * $cart[$i]->quantity; ?></td>
  </tr>

  <?php 
 $index++;
 $quantitycart=$cart[$i]->quantity;

   }
      if(array_key_exists('submit', $_POST))
      {  $results = mysqli_query($con, "select * from products"); 

     while($products= mysqli_fetch_object($results)){
     for($i=0; $i<count($cart); $i++){    
     $quantity= $products->quantity;
     $idcart=$cart[$i]->id;


     $sql = "UPDATE products SET quantity= quantity -'$quantitycart' WHERE 
 id='$idcart'";
    }}
 if ($con->query($sql) === TRUE) {
    echo "Record updated successfully";
 } else {
    echo "Error updating record: " . $con->error;
}

The problem is with the $idcart. For some reason it isn't properly looping and giving the right id's only the last one in the cart too. Any help would be appreciated.

Thank you.

The problem lies in the loop, where your sql query will be got over written in each loop so the last sql query will be executed. So you can append the sql query each time and execute it using multi_query method

    if(array_key_exists('submit', $_POST))
      {  $results = mysqli_query($con, "select * from products"); 
     $sql="";//init
     while($products= mysqli_fetch_object($results)){
     for($i=0; $i<count($cart); $i++){    
     $quantity= $products->quantity;
     $idcart=$cart[$i]->id;
     $sql .= "UPDATE products SET quantity= quantity -'$quantitycart' WHERE 
     id='$idcart';";//here u need to append the query
    }//end for
    }//end while
    if ($con->multi_query($sql) === TRUE) {//use multi_query
    echo "Record updated successfully";
    } else {
    echo "Error updating record: " . $con->error;
    }

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