簡體   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