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.