我試圖在PHP中創建一個簡單的購物車。我設法將項目添加到會話中。如果您添加相同的項目數量更新。購物車刪除所有數量而不是一個
但是,當我刪除一個數量大於1的項目時,它將刪除該項目的所有內容,而不是從數量中刪除1。
我想知道是否有人可以檢查我可能會做錯什麼?
重視產品的ID:
<a href="checkout.php?id=<?php echo $earthProducts -> id; ?>"> Order Now </a>
我有一個項目類:
<?php
Class Item{
var $id;
var $name;
var $price;
var $quantity;
}
?>
在結帳頁面將顯示當前在購物車中的所有產品:
require 'item.php';
if (isset($_GET['id'])) {
$result = mysqli_query($con, 'SELECT * FROM earthProducts WHERE id=' . $_GET['id']);
$earthProducts = mysqli_fetch_object($result);
$item = new Item();
$item->id = $earthProducts->id;
$item->name = $earthProducts->name;
$item->price = $earthProducts->price;
$item->quantity = 1;
// Check product is existing in cart
$index = -1;
$cart = unserialize(serialize($_SESSION['cart']));
for ($i = 0; $i < count($cart); $i++)
if ($cart[$i]->id == $_GET['id']) {
$index = $i;
break;
}
if ($index == -1) {
$_SESSION['cart'] [] = $item;
} else {
$cart[$index]->quantity++;
$_SESSION['cart'] = $cart;
}
}
?>
然後我用一個按鈕打印購物車刪除該項目:
<table cellpadding="2" cellspacing="2" border="1">
<tr>
<th>Option</th>
<th>Id</th>
<th>Name</th>
<th>Price</th>
<th>Quantity</th>
<th>Sub Total</th>
</tr>
<?php
$cart = unserialize(serialize($_SESSION['cart']));
$s = 0;
$index = 0;
for ($i = 0; $i < count($cart); $i++) {
$s += $cart[$i]->price * $cart[$i]->quantity;
?>
<tr>
<td> <a href="checkout.php?index=<?php echo $index; ?>" onclick="return confirm('Are you sure?')">Delete</td>
<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++;
}
?>
<tr>
<td colspan="4" align="right">Sum</tr>
<td align="left"> <?php echo $s ?></td>
</table>
<br>
<a href="earth_products.php"> Continue Shopping </a>
<br>
<br>
<?php
print_r($cart);
?>
我的代碼放入購物車中刪除項目(這是錯誤的):
// Delete product in cart
if (isset($_GET['index'])) {
$cart = unserialize(serialize($_SESSION['cart']));
unset($cart[$_GET['index']]);
$cart = array_values($cart);
$_SESSION['cart'] = $cart;
}
所以,如果我有項目-1的1數量,我按Delete鍵將其刪除。如果我擁有數量爲2的item-2,它將刪除這兩個數量並從購物車中刪除item-2。
如果有人能提供幫助,請事先致謝。
完美,非常感謝您的支持! – Brent