简体   繁体   English

如何使用Cookie方法将多个项目添加到购物车

[英]how to add multiple items to cart with cookies method

when i add second item to the cart , the first item will be replaced 当我将第二个项目添加到购物车时,第一个项目将被替换
this is my code(cart.php) 这是我的代码(cart.php)

<?php 
    include"connect.php";
 ?>

<?php
   $total=0;
$variety = $quantity = $bran = "";

if(isset($_COOKIE['cart']))
{
$cookie = $_COOKIE['cart'];
$cookie = stripslashes($cookie);
$savedCardArray = json_decode($cookie, true);
foreach ($savedCardArray as $key => $value) {
    $variety=$savedCardArray[$key][0];
    $quantity=$savedCardArray[$key][1];
    $bran=$savedCardArray[$key][2];
    $total = $quantity*998;
    setcookie('total', $total);
}

}
?>

the cart_update page is given below cart_update页面如下

<?php
class CartUpdate 
{

    /**
     * Initialize the Cart.
     * @return void
     */
    public function __construct() {

        if(isset($_COOKIE['cart'])) {

            $cookie = $_COOKIE['cart'];
            $cookie = stripslashes($cookie);
            $savedCardArray = json_decode($cookie, true);

         }
    }


    function add()
    {
        $variety = test_input($_POST["variety"]);  
        $rice_type = test_input($_POST["rice_type"]);
        $quantity = test_input($_POST["quantity"]);
        $bran = test_input($_POST["bran"]);
        $items[]=array($variety,$quantity,$bran,$rice_type);
        $json = json_encode($items);    
        setcookie('cart', $json);
    }

i need all selected items in cart with this cookies method. 我需要使用此cookie方法的购物车中所有选定的项目。 could anyone help me?? 有人可以帮我吗?

My PHP is a bit rusty these days but it seems every time you call add() method on Cart object you rewrite your cookie. 这些天我的PHP有点生锈,但是似乎每次您在Cart对象上调用add()方法时,都会重写cookie。 In your Cart constructor you read cookie contents into local var $savedCardArray (typo?) but then you operate on local var $items in your add() method, add new element to it and save the cookie. 在您的Cart构造函数中,您将cookie内容读入本地var $savedCardArray (typo?),但是随后您在add()方法中对本地var $items进行了操作,向其中添加了新元素并保存了cookie。

I would suggest refactoring this code. 我建议重构此代码。 First of all is there any special reason this class is called CartUpdate? 首先,将此类称为CartUpdate有什么特殊原因吗? Just name it Cart. 只需将其命名为购物车即可。 In constructor read in cookie into instance variable so once you read the contents from cookie you can then access it in other methods of Cart instance. 在构造函数中,将cookie读入实例变量,这样一旦您从cookie中读取了内容,就可以在Cart实例的其他方法中对其进行访问。 You can also provide get() method to return array of items in the cart and total() method that will calculate total price. 您还可以提供get()方法以返回购物车中的商品数组,以及提供total()方法来计算总价。

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

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