【问题标题】:php Add to the basket with a given quantityphp 以给定数量添加到购物篮
【发布时间】:2017-03-03 13:26:45
【问题描述】:

我正在尝试制作一个简单的目录,在购物车中添加并订购,但我有一个问题:在购物车中添加所需数量的产品时一切正常,但如果我想添加另一个,然后什么都没有出来。它只是将数量更新为 1。

表格:

<form action="buy.php" method="post">
    <input type="hidden" name="productId" value="<?php echo $product['id']; ?>">
    <?php if ($product['quantity'] === 0): ?>
        <button type="submit" name="submit" disabled="true">Not available</button>
    <?php else: ?>
        <inputtype="number" name="productQuantity" value="1">
        <button type="submit" name="submit">Add to cart</button>
    <?php endif; ?>
</form>

购买.php

<?php

session_start();

if (isset($_POST['submit'])) {
    $productId = $_POST['productId'];

    $productQuantity = $_POST['productQuantity'];

    $_SESSION['cart'][$productId] = [
        'quantity' => $productQuantity
    ];
}

header('Location: http://localhost:8000/');

【问题讨论】:

    标签: php session post cart


    【解决方案1】:

    问题是您正在用新条目覆盖整个会话变量。而不是将条目添加到数组中。

    尝试使用此代码:

    <?php
    
    session_start();
    
    if (isset($_POST['submit'])) {
        $productId = $_POST['productId'];
    
        $productQuantity = $_POST['productQuantity'];
    
        $_SESSION['cart'][] = array('id' => $productId, 'quantity' => $productQuantity);
    }
    
    header('Location: http://localhost:8000/');
    

    使用此代码,您将拥有一个包含所有条目的数组。我想这也更容易使用。

    【讨论】:

    • 谢谢!我找到了解决方案: $_SESSION['cart'][$productId]['quantity'] += $productQuantity;
    猜你喜欢
    • 1970-01-01
    • 2012-03-02
    • 2012-06-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-05
    • 2015-04-29
    • 1970-01-01
    相关资源
    最近更新 更多