diff --git a/cart.php b/cart.php index 56719289289c442fa9bfbcbe0c4849d2d3d0c50d..34cb2f296beff01d147cffcd6b9c4e9660788cab 100644 --- a/cart.php +++ b/cart.php @@ -11,8 +11,8 @@ if (!isset($_SESSION['user_id'])) { // ✅ เพิ่มสินค้าเข้า `cart` if (isset($_GET['add'])) { $stmt = $conn->prepare(" - INSERT INTO cart (users_id, products_id, qty) - VALUES (?, ?, 1) + INSERT INTO cart (id, users_id, products_id, qty) + VALUES (NULL, ?, ?, 1) ON DUPLICATE KEY UPDATE qty = qty + 1 "); $stmt->execute([$_SESSION['user_id'], $_GET['add']]); @@ -20,6 +20,23 @@ if (isset($_GET['add'])) { exit; } +// ✅ อัปเดตจำนวนสินค้า +if (isset($_GET['update']) && isset($_GET['qty'])) { + $qty = max(1, intval($_GET['qty'])); // ป้องกันค่าติดลบ + $stmt = $conn->prepare("UPDATE cart SET qty = ? WHERE users_id = ? AND products_id = ?"); + $stmt->execute([$qty, $_SESSION['user_id'], $_GET['update']]); + header("Location: cart.php"); + exit; +} + +// ✅ ลบสินค้าออกจาก `cart` +if (isset($_GET['remove'])) { + $stmt = $conn->prepare("DELETE FROM cart WHERE users_id = ? AND products_id = ?"); + $stmt->execute([$_SESSION['user_id'], $_GET['remove']]); + header("Location: cart.php"); + exit; +} + // ✅ ดึงข้อมูลจาก `cart` และ `products` $stmt = $conn->prepare(" SELECT cart.*, products.name, products.price @@ -36,8 +53,6 @@ $cart_items = $stmt->fetchAll(PDO::FETCH_ASSOC); <?php if (empty($cart_items)): ?> <p>ไม่มีสินค้าในตะกร้า</p> <?php else: ?> - - <table border="1" cellpadding="5" cellspacing="0"> <tr> <th>User ID</th> @@ -56,12 +71,12 @@ $cart_items = $stmt->fetchAll(PDO::FETCH_ASSOC); $total += $subtotal; ?> <tr> - <td><?= $item['users_id'] ?></td> + <td><?= $item['users_id'] ?></td> <td><?= $item['products_id'] ?></td> <td><?= htmlspecialchars($item['name']) ?></td> <td><?= number_format($item['price'], 2) ?> บาท</td> <td> - <a href="cart.php?update=<?= $item['products_id'] ?>&qty=<?= $item['qty'] - 1 ?>">➖</a> + <a href="cart.php?update=<?= $item['products_id'] ?>&qty=<?= max(1, $item['qty'] - 1) ?>">➖</a> <?= $item['qty'] ?> <a href="cart.php?update=<?= $item['products_id'] ?>&qty=<?= $item['qty'] + 1 ?>">➕</a> </td> @@ -70,7 +85,7 @@ $cart_items = $stmt->fetchAll(PDO::FETCH_ASSOC); </tr> <?php endforeach; ?> <tr> - <td colspan="4" align="right"><strong>ยอดรวมทั้งหมด:</strong></td> + <td colspan="5" align="right"><strong>ยอดรวมทั้งหมด:</strong></td> <td colspan="2"><strong><?= number_format($total, 2) ?> บาท</strong></td> </tr> </table>