我正在尝试更新保存在数组中的数量值,因此当我更新数量时,它也会在刷新后保存。问题是,当我总是更新相同的项目时,即使我在购物车中有多个项目并且我尝试更改每个项目的数量,它也只会更改一个项目的数量。我在这些循环中有点迷失,我试图将更新部分移出,但它没有帮助。此外,当我没有unset($_POST['qt'])
时,它会更改购物车中的所有商品数量,这是错误的。
foreach ($_SESSION['cart'] as $index => $item) {
foreach ($item as $id => $quantity) {
$sql = "SELECT name, image, quantity, price FROM product WHERE product.id_p = ?";
$stmt = $db->prepare($sql);
$stmt->bind_param('s', $id);
$stmt->execute();
$stmt->bind_result($name, $image, $maxquantity, $price);
while($stmt->fetch()) : ?>
<tr>
<td><?=$image?></td>
<td><?=$name?></td>
<td><?=$id?></td>
<td><input type="number" class="form-control quantitycart" data-id="<?=$id?>" min="1" max="<?=$maxquantity?>" data-min="1" data-max="<?=$maxquantity?>" name="quantitycart" value="<?=$quantity = ($quantity > $maxquantity) ? $maxquantity : $quantity; ?>"/></td>
<td>€<span class="price"><?=$price * $quantity?></span>
<input type="hidden" class="real_price" value="<?=$price?>"/></td>
<td><a href="cart.php?delete=<?=$id; ?>" class="btn btn-xs btn-default"><?=$id?><span class="glyphicon glyphicon-remove-sign"/></a></td>
<tr>
<?php
if(isset($_POST['qt']) && isset($_POST['idupd'])){
$_SESSION['cart'][$index][$_POST['idupd']] = $_POST['qt'];
unset($_POST['qt']);
unset($_POST['idupd']);
}
endwhile;
$stmt->close(); }
}
}
JS
$('.quantitycart').change(function(){
var container = $(this).parents('tr');
var price = container.find('.real_price').val() * 1;
var qty = $(this).val() * 1;
var total = price * qty;
var id = $(this).data('id');
container.find('.price').html(total);
$.ajax({
type: 'POST',
cache: false,
data: {qt: qty, idupd: id},
url: 'includes/cartbody.php',
success: function(data){
}
});
});
编辑:
if(isset($_POST['qt']) && isset($_POST['idupd'])){
$_SESSION['cart'][$index][$_POST['idupd']] = $_POST['qt'];
unset($_POST['qt']);
unset($_POST['idupd']);
}