无法将商品添加到购物车文件

问题描述 投票:0回答:1

我有一个 item.php 文件和 cart.php 文件。 我正在尝试将 item.php 文件中的商品添加到 cart.php 文件中的购物车。 我正在从名为:menu

的数据库表中提取每个项目的详细信息

由于某种原因,按“添加到购物车”按钮无法添加到 cart.php。我已经尝试了几个小时,但仍然无法工作。有人可以帮我吗?

这是我的 item.php:

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

// Add your database connection logic here
$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);
}

// Check if the item ID is provided in the URL
if (!isset($_GET['id'])) {
    // Redirect or display an error message
    echo "Item ID not provided.";
    exit();
}

$itemID = $_GET['id'];

// 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'];
    $itemDescription = $row['item_description'];
    $itemCategory = $row['item_category'];
    $itemPrice = $row['item_price'];
    $itemPhoto = $row['item_photo'];
} else {
    // Redirect or display an error message
    echo "Item not found.";
    exit();
}

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

    // 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();
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo $itemName; ?></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: 0px;
        }

        .item-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 */
        }

        img {
            width: 100%;
            max-width: 500px;
            height: auto;
        }

        /* Add your additional styles here */
        form {
            display: flex;
            flex-direction: column;
            align-items: flex-start;
            margin-top: 20px;
        }

        label {
            margin-bottom: 5px;
        }

        select {
            margin-bottom: 10px;
        }
    </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">
    <!-- Display item details -->
    <div class="item-details">
        <img src="<?php echo $itemPhoto; ?>" alt="<?php echo $itemName; ?>">
        <h2><?php echo $itemName; ?></h2>
        <p><?php echo $itemDescription; ?></p>
        <p>Category: <?php echo $itemCategory; ?></p>
        <p>Price: RM <?php echo $itemPrice; ?></p>

        <!-- Add to Cart Form -->
        <form method="post" action="cart.php?action=add&id=<?php echo $itemID; ?>">
            <label for="quantity">Quantity:</label>
            <select name="quantity" id="quantity">
                <?php
                // Generate options for quantity dropdown (you can set a maximum limit if needed)
                for ($i = 1; $i <= 10; $i++) {
                    echo '<option value="' . $i . '">' . $i . '</option>';
                }
                ?>
            </select>
            <input type="submit" name="add_to_cart" value="Add to Cart">
        </form>
    </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>

这是我的 cart.php:

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

// Debugging statement
echo "Debug: Session ID: " . session_id() . "<br>";

// 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>
                    </tr>
                    <?php
                    foreach ($_SESSION['shopping_cart'] as $key => $value) {
                        ?>
                        <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>
                        </tr>
                        <?php
                        $total += $value['item_price'] * $value['item_quantity'];
                    }
                    ?>
                    <tr>
                        <td colspan="2" 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.";
}
?>

我已经尝试调试了几个小时,但仍然无法弄清楚。我不认为这是来自数据库的错误,更多的是来自代码逻辑问题,但我只是无法弄清楚...... 有人可以帮我吗?

php html forms cart
1个回答
0
投票

item.php
中的代码仅在收到 POST 请求时才会向会话购物车添加一些内容:

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['add_to_cart'])) {

但是您显示的 POST 到该页面的代码中没有任何表单。

item.php
上的表单会发布到
cart.php
,但该页面根本不会执行任何操作,除非会话购物车中有东西。

我猜这个代码在

item.php

// Handle Add to Cart action
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['add_to_cart'])) {
    // ... all this code
}

确实应该位于

cart.php
的顶部。这样,当您在
item.php
上提交表单时,
cart.php
会收到 POST,移动的代码块将处理请求并将商品添加到购物车,然后该页面将显示购物车内容。

其他一些观察:

  • 您的代码对 SQL 注入开放使用 PDO 和参数

  • 这里有很多与问题完全无关的代码(例如你的CSS、JS、大部分HTML),这只会让人们更难看到和理解问题。如果您尝试创建一个最小问题示例,那么其他人可以更轻松地提供帮助。

© www.soinside.com 2019 - 2024. All rights reserved.