【问题标题】:Increase quantity values in $_SESSION when adding same product添加相同产品时增加 $_SESSION 中的数量值
【发布时间】:2016-02-27 09:19:12
【问题描述】:

我想通过单击添加到相同产品的购物车来添加更多数量,但我的代码使用的最大数量为 2。

我的代码:

cart_process.php

if(isset($_POST["product_code"]))
{
    foreach($_POST as $key => $value){
        $new_product[$key] = filter_var($value, FILTER_SANITIZE_STRING); //create a new product array 
    }

    //we need to get product name and price from database.
    $statement = $mysqli_conn->prepare("SELECT product_name, product_price FROM products_list WHERE product_code=? LIMIT 1");
    $statement->bind_param('s', $new_product['product_code']);
    $statement->execute();
    $statement->bind_result($product_name, $product_price);


    while($statement->fetch()){ 
        $new_product["product_name"] = $product_name; //fetch product name from database
        $new_product["product_price"] = $product_price;  //fetch product price from database
        $new_product["product_qty"] = 1;

        if(isset($_SESSION["products"])){  //if session var already exist
            if(isset($_SESSION["products"][$new_product['product_code']])) //check if item already exist in products array add more quantity +1
            {
                $_SESSION["products"][$new_product['product_code']] = $new_product["product_qty"]++;
            }           
        }

        $_SESSION["products"][$new_product['product_code']] = $new_product; //update products with new item array       //update products with new item array   

    }

    $total_items = count($_SESSION["products"]); //count total items
    die(json_encode(array('items'=>$total_items))); //output json 

}

第一次点击添加到购物车时的输出:

Array
(
    [products] => Array
        (
            [TSH1] => Array
                (
                    [product_color] => Red
                    [product_size] => M
                    [product_code] => TSH1
                    [product_name] => Cool T-shirt
                    [product_price] => 8.50
                    [product_qty] => 1
                )

        )

)

并在第二次单击时输出再次将相同的产品添加到购物车:

[product_qty] => 2 // Quantity has been added when I click add the same product to cart

但是当我再次点击将相同的产品添加到购物车时,它不会添加更多数量。

【问题讨论】:

    标签: php session


    【解决方案1】:

    取消设置 [product_qty] 并增加计数器 ... 添加回会话数组

    【讨论】:

    • unset($_SESSION["products"][$new_product['product_qty']]) 对吗?
    猜你喜欢
    • 2017-12-19
    • 1970-01-01
    • 2013-12-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多