向篮子项目添加数量是添加新项目

时间:2017-01-06 16:28:43

标签: php session session-variables

我正在创建一个篮子,我想要的是如果再次添加已经在篮子中的项目,原始项目的数量将附加1。

当我添加一个已经在购物篮中的商品时,会添加一个新商品,并且可以通过点击原始商品上的+1来追加这个新商品的数量。

basket.php

<?php
  foreach ($_SESSION["basket"] as $basketItemArray) {                   
?>

<form role="form" action="includes/functions/create_shopping_cart.php" method="post">
    <button type="submit" name="basket-button" class="btn btn-default" value="<?php echo $basketItemArray["item_id"]; ?>"><i class="fa fa-plus" aria-hidden="true"></i></button>
    <? echo $basketItemArray["quantity"]; ?>
    <button class="btn btn-default"><i class="fa fa-minus" aria-hidden="true"></i></button>
</form>

上述表单通过+按钮的值发送 item_id

create_shopping_cart.php

$product_id = $_POST['basket-button'];
$sql = "SELECT * FROM menu WHERE product_id='".$product_id."'";

$result = $connection->query($sql);
$row = $result->fetch_assoc();

if (empty($_SESSION["basket"])) {
    $_SESSION["basket"]  = array( 

    array( "item_id"=>$row['product_id'], "item_name"=>$row['name'],"quantity"=>1 , "price"=>$row['price']) );

} else {
    // There is already a basket to append to
    $current_basket = $_SESSION["basket"];

    $found = false;
    foreach($_SESSION['basket'] as $product)
    {
        if($product_id == $product['item_id']) {
            $found = true;
            break;
        }
    }

    if($found)
    {
        $_SESSION['basket'][$product_id]['quantity'] ++;               
    } else {
        $new_basket  = array( 

        array( "item_id"=>$row['product_id'], "item_name"=>$row['name'],"quantity"=>1 , "price"=>$row['price']) );

        $_SESSION['basket'] = array_merge($current_basket, $new_basket);      
    } 
}

结果 This is what the result of clicking the + button on the original item twice

1 个答案:

答案 0 :(得分:1)

您没有定位/使用购物篮中的产品索引。 试试这个:

$product_id = $_POST['basket-button'];
$sql = "SELECT * FROM menu WHERE product_id='".$product_id."'";

$result = $connection->query($sql);
$row = $result->fetch_assoc();

if (empty($_SESSION["basket"])) {
    $_SESSION["basket"]  = array( 

    array( "item_id"=>$row['product_id'], "item_name"=>$row['name'],"quantity"=>1 , "price"=>$row['price']) );

} else {
    // There is already a basket to append to
    $current_basket = $_SESSION["basket"];

    $found = false;
    $id = '';
    foreach($_SESSION['basket'] as $key=>$product)
    {
        if($product_id == $product['item_id']) {
            $found = true;
            $id    = $key;
            break;
        }
    }

    if($found)
    {
        $_SESSION['basket'][$id]['quantity']++;               
    } else {
        $new_basket  = array( 

        array( "item_id"=>$row['product_id'], "item_name"=>$row['name'],"quantity"=>1 , "price"=>$row['price']) );

        $_SESSION['basket'] = array_merge($current_basket, $new_basket);      
    } 
}

您的代码可以进行更多优化,但现在让它正常工作更为重要。