You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

cart.php购物车出现无法删除的空条目问题求助

问题:购物车始终存在无法删除的空条目

商品可正常添加至cart.php的购物车,但购物车中始终显示一个空条目:无商品名称,数量为1,价格为RM0.00,且删除功能无法将其移除。

购物车中的空条目

相关代码

<?php
// Start the session
session_start();

// Handle Add to Cart action
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['add_to_cart'])) {
    // Sanitize input data
    $itemID = $_GET['id'];
    $quantity = isset($_POST['quantity']) ? intval($_POST['quantity']) : 1;

    // Add your database connection logic here (same as in item.php)
    $servername = "localhost"; // Change this to your MySQL server address
    $username = "root"; // Change this to your MySQL username
    $dbpassword = ""; // Change this to your MySQL password
    $dbname = "fyp"; // Change this to your database name

    $conn = new mysqli($servername, $username, $dbpassword, $dbname);

    if ($conn->connect_error) {
        die("Connection failed: " . $conn->connect_error);
    }

    // Fetch item details based on the provided item ID
    $sql = "SELECT * FROM menu WHERE item_id = '$itemID'";
    $result = $conn->query($sql);

    if ($result->num_rows > 0) {
        $row = $result->fetch_assoc();
        $itemName = $row['item_name'];
        $itemPrice = $row['item_price'];

        // Create an array to hold item details
        $itemArray = array(
            'item_id' => $itemID,
            'item_name' => $itemName,
            'item_price' => $itemPrice,
            'item_quantity' => $quantity
        );

        // Add item to the shopping cart
        if (!empty($_SESSION['shopping_cart'])) {
            // Check if the item is already in the cart, update quantity
            $itemIndex = -1;
            foreach ($_SESSION['shopping_cart'] as $key => $value) {
                if ($value['item_id'] === $itemID) {
                    $itemIndex = $key;
                    break;
                }
            }

            if ($itemIndex !== -1) {
                $_SESSION['shopping_cart'][$itemIndex]['item_quantity'] += $quantity;
            } else {
                // Add the new item to the existing cart
                array_push($_SESSION['shopping_cart'], $itemArray);
            }
        } else {
            // Create a new shopping cart
            $_SESSION['shopping_cart'] = array($itemArray);
        }

        $conn->close();
    }
}

// Handle Delete Item action
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['delete_item'])) {
    $deleteItemID = $_POST['delete_item_id'];

    // Remove the item from the shopping cart
    foreach ($_SESSION['shopping_cart'] as $key => $value) {
        if ($value['item_id'] === $deleteItemID) {
            unset($_SESSION['shopping_cart'][$key]);
            break;
        }
    }

    // Reset array keys after unset
    $_SESSION['shopping_cart'] = array_values($_SESSION['shopping_cart']);
}

// Check if the cart is empty
if (!empty($_SESSION['shopping_cart'])) {
    // Display cart items
    $total = 0;
    ?>
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Cart</title>
        <!-- Add your CSS styling here -->
        <style>
            /* Add your CSS styles */
            body {
                font-family: Arial, sans-serif;
                margin: 0;
                padding: 0;
            }

            header {
                background-color: #333;
                color: #fff;
                padding: 10px;
                display: flex;
                justify-content: space-between;
                align-items: center;
            }

            header img {
                height: 40px;
                width: auto; /* Adjusted width to maintain aspect ratio */
            }

            header div {
                display: flex;
                align-items: center; /* Align items vertically */
            }

            header div span {
                font-size: 18px;
                color: #fff;
                margin-right: 10px; /* Added margin to separate user ID and cart icon */
            }

            .sidebar {
                height: 100%;
                width: 250px;
                position: fixed;
                z-index: 1;
                top: 0;
                left: -250px;
                background-color: #fff; /* Change to white color */
                overflow-x: hidden;
                transition: 0.5s;
                padding-top: 60px;
            }

            .sidebar a {
                padding: 15px 8px 15px 32px;
                text-decoration: none;
                font-size: 24px; /* Increase font size */
                color: #818181;
                display: block;
                transition: 0.3s;
            }

            .sidebar a:hover {
                color: #333; /* Change hover color */
            }

            .main-content {
                display: flex;
                justify-content: center;
                align-items: center;
                height: 100vh; /* Set height to 100% of viewport height for centering */
                padding: 16px;
            }

            .cart-details {
                max-width: 600px; /* Adjusted max-width for responsiveness */
                text-align: left; /* Align text to the left */
                margin: 30px; /* Added margin between photo and details */
            }

            table {
                width: 100%;
                border-collapse: collapse;
                margin-top: 20px;
            }

            th, td {
                border: 1px solid #ddd;
                padding: 8px;
                text-align: left;
            }

            th {
                background-color: #f2f2f2;
            }

            .total-price {
                margin-top: 20px;
                font-weight: bold;
            }
        </style>
    </head>
    <body>

    <header>
        <img src="logo.png" alt="Restaurant Logo">
        <!-- Wrap the user icon inside an anchor tag -->
        <a href="accountdetails.php">
            <div>
                <img src="user-icon.png" alt="User Icon">
                <!-- Display user ID if available in the session -->
                <?php
                if (isset($_SESSION['user_id'])) {
                    echo '<span>' . $_SESSION['user_id'] . '</span>';
                }
                ?>
            </div>
        </a>
        <img src="cart-icon.png" alt="Cart Icon">
        <button onclick="toggleSidebar()">☰</button>
    </header>

    <!-- Sidebar -->
    <div class="sidebar">
        <a href="index.php">Home</a>
        <a href="menu.php">Menu</a>
        <a href="#">Order History</a>
        <a href="#">Review</a>
    </div>

    <!-- Main Content -->
    <div class="main-content">
        <!-- Cart Details -->
        <div class="cart-details">
            <h1>Cart</h1>
            <table>
                <tr>
                    <th>Item Name</th>
                    <th>Quantity</th>
                    <th>Price</th>
                    <th>Action</th>
                </tr>
                <?php
                foreach ($_SESSION['shopping_cart'] as $key => $value) {
                    if ($value['item_quantity'] > 0) {
                        ?>
                        <tr>
                            <td><?php echo $value['item_name']; ?></td>
                            <td><?php echo $value['item_quantity']; ?></td>
                            <td>RM <?php echo number_format($value['item_price'], 2); ?></td>
                            <td>
                                <form method="post">
                                    <input type="hidden" name="delete_item_id" value="<?php echo $value['item_id']; ?>">
                                    <button type="submit" name="delete_item" style="background: none; border: none; color: red; cursor: pointer;">Delete</button>
                                </form>
                            </td>
                        </tr>
                        <?php
                        $total += $value['item_price'] * $value['item_quantity'];
                    }
                }
                ?>
                <tr>
                    <td colspan="3" class="total-price">Total</td>
                    <td class="total-price">RM <?php echo number_format($total, 2); ?></td>
                </tr>
            </table>
        </div>
    </div>

    <script>
        // Function to toggle the sidebar
        function toggleSidebar() {
            var sidebar = document.querySelector('.sidebar');
            if (sidebar.style.left === "0px") {
                sidebar.style.left = "-250px";
            } else {
                sidebar.style.left = "0px";
            }
        }
    </script>

    </body>
    </html>
    <?php
    // Debugging statement
    echo "Debug: Cart is not empty.";
} else {
    echo "Your cart is empty.";
}
?>

原因分析与解决方案

核心原因

  1. Session残留无效数据:之前调试或错误操作导致$_SESSION['shopping_cart']中存入了无有效商品信息的条目,且未被正确清理。
  2. 输入校验缺失:未对$_GET['id']做有效性校验,若用户在无商品ID的情况下提交添加购物车请求,可能触发异常逻辑写入空数据。
  3. 显示与删除逻辑漏洞:显示时仅校验数量>0,未过滤无名称/ID的无效条目;删除逻辑依赖item_id匹配,若空条目无item_id或item_id为空,可能无法匹配删除。

解决步骤

1. 清空残留Session数据(临时测试)

在session_start();后添加以下代码,清空购物车Session,测试空条目是否消失:

// 临时添加,测试完成后删除
unset($_SESSION['shopping_cart']);

2. 新增商品ID有效性校验

在处理添加购物车的逻辑开头,加入对$_GET['id']的校验,防止无效请求:

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['add_to_cart'])) {
    // 新增:校验商品ID是否有效
    if (!isset($_GET['id']) || empty(trim($_GET['id']))) {
        die("无效的商品ID");
    }
    $itemID = trim($_GET['id']);
    $quantity = isset($_POST['quantity']) ? intval($_POST['quantity']) : 1;
    // ... 后续原有代码
}

3. 过滤无效购物车条目

在显示购物车时,新增对商品名称、ID的校验,过滤无效条目:

foreach ($_SESSION['shopping_cart'] as $key => $value) {
    // 新增:过滤无ID、无名称或数量无效的条目
    if (empty($value['item_id']) || empty($value['item_name']) || $value['item_quantity'] <= 0) {
        continue;
    }
    // ... 原有显示代码
}

4. 修复删除逻辑,兼容空ID场景

修改删除逻辑,确保能匹配并删除空ID的无效条目:

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['delete_item'])) {
    $deleteItemID = isset($_POST['delete_item_id']) ? trim($_POST['delete_item_id']) : '';

    foreach ($_SESSION['shopping_cart'] as $key => $value) {
        // 兼容item_id不存在的情况
        $currentItemID = isset($value['item_id']) ? trim($value['item_id']) : '';
        if ($currentItemID === $deleteItemID) {
            unset($_SESSION['shopping_cart'][$key]);
            break;
        }
    }
    $_SESSION['shopping_cart'] = array_values($_SESSION['shopping_cart']);
}

5. 修复SQL注入风险(可选但重要)

原代码直接拼接SQL存在注入风险,改用预处理语句:

// 替换原有SQL查询部分
$sql = "SELECT * FROM menu WHERE item_id = ?";
$stmt = $conn->prepare($sql);
$stmt->bind_param("s", $itemID);
$stmt->execute();
$result = $stmt->get_result();

if ($result->num_rows > 0) {
    $row = $result->fetch_assoc();
    $itemName = $row['item_name'];
    $itemPrice = $row['item_price'];
    // ... 后续原有代码
}
$stmt->close();

内容的提问来源于stack exchange,提问作者Yyaann

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.02 14:42:03