douduonang3169
douduonang3169
2017-12-05 05:07

如何正确循环和更新数据库中的数量。

已采纳

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.

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

1条回答

  • douhui8454 douhui8454 4年前

    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;
        }
    
    点赞 评论 复制链接分享

为你推荐