繁体   English   中英

使用会话变量在购物车中添加和删除商品

[英]Add and remove items from shopping cart using session variables

我正在创建一个购物车。 添加和删​​除项目功能的两个问题。 添加购物车中已有的项目时,它不会覆盖现有的项目,从而导致购物车中同一项目的两个实例。 删除项目仅适用于列表中最上面的项目。

    switch($_GET["action"])
    {
        case "add":
        if(!empty($_POST["quantity"])) 
        {
            $id=$_POST["id"];
            $result = $mysqli->query("SELECT * FROM menu WHERE itemid='$id'");
            while($itembyId=$result->fetch_assoc())
            {
                $itemArray = array($id=>array('name'=>$_POST["name"],
                 'id'=>$id, 'quantity'=>$_POST["quantity"], 'details'=>$_POST["details"],
                  'price'=>$_POST["price"]));

                if(!empty($_SESSION["cart_item"])) 
                {
                    if(in_array($itembyId["itemid"],$_SESSION["cart_item"])) 
                    {
                        foreach($_SESSION["cart_item"] as $k => $v)
                        {   
                                if($itembyId["itemid"] == $k)
                                    $_SESSION["cart_item"][$k]["quantity"] = $_POST["quantity"];
                        }
                    }
                    else
                    {
                        $_SESSION["cart_item"] = array_merge($_SESSION["cart_item"],$itemArray);
                    }
                } 
                else 
                {
                    $_SESSION["cart_item"] = $itemArray;
                }
            }
        }
        break;
        case "remove":
            if(!empty($_SESSION["cart_item"]))
             {
                foreach($_SESSION["cart_item"] as $k => $v)
                 {
                        if($_GET["id"] == $k)
                            unset($_SESSION["cart_item"][$k]);              
                        if(empty($_SESSION["cart_item"]))
                            unset($_SESSION["cart_item"]);
                }
            }

这对我行得通! 这是增加数量的选择...

<form action="xxxx" method="POST"><input type="hidden" name="type" value="update_suma" /><input type="hidden" name="id" value="'.$item["id"].'" /><input type="submit"value="+" /></form>


<pre>case "update_suma":
        if(!empty($_SESSION["cart_item"])) {
            foreach($_SESSION["cart_item"] as $k => $v) {
                    if($_POST["identidad"] == $_SESSION["cart_item"][$k]['id'])

                       $_SESSION["cart_item"][$k]["cantidad"]++;    

            }
        }

break;</pre>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM