简体   繁体   中英

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)

<?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

<?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. 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. 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.

I would suggest refactoring this code. First of all is there any special reason this class is called 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. You can also provide get() method to return array of items in the cart and total() method that will calculate total price.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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