添加数量到购物篮项目是添加一个新项目

Adding quantity to basket item is adding a new item

我正在创建一个购物篮,我想要的是,如果再次添加一个已经在购物篮中的商品,原始商品的数量将附加 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);      
    } 
}

结果

您不是targeting/using购物篮中商品的索引。 试试这个:

$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);      
    } 
}

您的代码可以进一步优化,但目前更重要的是让它正常工作。