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

基于PHP Session实现多商品加入购物车的技术求助

Hey there! Let's tackle those two shopping cart issues you're dealing with—they're super common when building session-based carts in PHP, so we'll get them sorted out quickly.


Issue 1: New Products Overwriting Existing Cart Items

What's Going Wrong

Right now, your code is storing only the quantity for each product in $_SESSION['basket'], and when you add a new product, it's replacing the existing entry instead of appending it. For example, $_SESSION['basket'][$_REQUEST['name']] = $_REQUEST['quantity'] just sets a single value per product, not a structured entry that keeps track of price and quantity together.

The Fix (basket_page.php)

Update the add_product action block to store each product as an array with both price and quantity, and handle existing items by incrementing their quantity instead of overwriting:

if($_REQUEST['action']=='add_product'){
    // Sanitize and validate inputs first
    $productName = htmlspecialchars($_REQUEST['name']);
    $productPrice = (float)$_REQUEST['price'];
    $productQty = max(1, (int)$_REQUEST['quantity']); // Ensure quantity is at least 1

    // Check if the product is already in the cart
    if(isset($_SESSION['basket'][$productName])){
        // Add to the existing quantity
        $_SESSION['basket'][$productName]['quantity'] += $productQty;
    } else {
        // Add a new product entry to the cart
        $_SESSION['basket'][$productName] = [
            'price' => $productPrice,
            'quantity' => $productQty
        ];
    }
}

Then, fix the cart display to loop through the session data (instead of relying on $_REQUEST, which disappears after a page reload):

<div class="col-25">
    <div class="container">
        <h4>Cart <span class="price" style="color:black">
            <i class="fa fa-shopping-cart"></i>
        </span></h4>
        <br><br>
        <?php 
        $total = 0;
        // Loop through all items in the session basket
        foreach($_SESSION['basket'] as $productName => $item): 
            $itemTotal = $item['price'] * $item['quantity'];
            $total += $itemTotal;
        ?>
            <p>
                <span class="name"><?= $productName ?> (x<?= $item['quantity'] ?>)</span>
                <span class="price"><?= $pound ?><?= number_format($itemTotal, 2) ?></span>
            </p>
        <?php endforeach; ?>
        <hr>
        <p>Total <span class="price" style="color:black"><b><?= $pound ?><?= number_format($total, 2) ?></b></span></p>
    </div>
</div>

Issue 2: Quantity Input Value Not Passing to the Cart

What's Going Wrong

Your "Add to Basket" link has a hardcoded quantity=1 parameter, so it never reads the value from the number input field. The link doesn't update when the user changes the quantity, so it always sends 1 to the cart.

The Fix (prod_details.php)

We have two solid options here—pick whichever fits your workflow better:

Option 1: Use JavaScript to Update the Link

First, give your quantity input an ID so we can target it:

<input type="number" id="quantityInput" min="1" max="9" step="1" value="1">

Then, update your "Add to Basket" link to have an ID, and add a script to update its quantity parameter whenever the input changes:

<a href="#" id="addToBasketBtn" class="cart-btn">Add to Basket</a>

<script>
$(document).ready(function () {
    // Keep your existing color change code here...

    // Handle quantity updates for the add to basket link
    const quantityInput = $('#quantityInput');
    const addToBasketBtn = $('#addToBasketBtn');
    // Base URL without the quantity parameter
    const baseUrl = "basket_page.php?action=add_product&name=<?= urlencode($productdetails['prod_Name']) ?>&price=<?= $productdetails['prod_Price'] ?>";

    // Update the link when the page loads
    updateBasketLink();

    // Update the link whenever the quantity input changes
    quantityInput.on('change input', updateBasketLink);

    function updateBasketLink() {
        const selectedQty = quantityInput.val();
        addToBasketBtn.attr('href', `${baseUrl}&quantity=${selectedQty}`);
    }
});
</script>

Option 2: Use a Form (More Reliable, No JS Dependency)

Replace the link with a form that submits the quantity value directly—this works even if the user has JavaScript disabled:

<div class="product-price">
    <span><?=$pound?><?= htmlspecialchars($productdetails['prod_Price'])?></span>
    <form action="basket_page.php" method="GET">
        <input type="hidden" name="action" value="add_product">
        <input type="hidden" name="name" value="<?= htmlspecialchars($productdetails['prod_Name']) ?>">
        <input type="hidden" name="price" value="<?= $productdetails['prod_Price'] ?>">
        <div class="quantity">
            <span>Quantity</span>
            <br>
            <input type="number" name="quantity" min="1" max="9" step="1" value="1">
        </div>
        <button type="submit" class="cart-btn">Add to Basket</button>
    </form>
</div>

(Note: If you go with this option, you can remove the original separate quantity div since it's now part of the form.)


Quick Security Note

Always sanitize user input to avoid XSS attacks and invalid data! We added htmlspecialchars for product names and cast values to appropriate types (float for price, int for quantity) in the basket code—this helps keep your cart safe and reliable.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.29 13:17:37