/ / Wie aktualisiere ich ein Array innerhalb eines Cookies? - PHP, Arrays, Cookies

Wie aktualisiere ich ein Array innerhalb eines Cookies? - PHP, Arrays, Cookies

Ich spare ein Warenkorb-Array in einem Cookie, um zu sendenes zur Einkaufswagenseite. Wenn ich von einem anderen Produkt auf eine Seite zugreife und auf Add to cart klicke, fügt es es nicht zum Array hinzu, sondern scheint es zu überschreiben.

$uri = $_SERVER["REQUEST_URI"];
$pin = explode("/", $uri);
$id = $pin[3];

$product = $model->selectById($id, "carpet");
$product = $product->fetch(PDO::FETCH_ASSOC);

$site_url = site_url();
if(!$product){
header("Location: $site_url./404");
}

if(isset($_POST["add"])){
$cart = [];
$cart[$product["id"]] = [];
$cart[$product["id"]]["product_name"] = $product["name"];

setcookie("cart", serialize($cart), time()+3600);
$cart = unserialize($_COOKIE["cart"]);
dd($cart);
}

Antworten:

0 für die Antwort № 1

Sie haben die Antwort bereits gegeben: Sie überschreiben den Einkaufswagen jedes Mal, wenn dieses Skript ausgeführt wird. Änderungen:

$uri = $_SERVER["REQUEST_URI"];
$pin = explode("/", $uri);
$id = $pin[3];

$product = $model->selectById($id, "carpet");
$product = $product->fetch(PDO::FETCH_ASSOC);

$site_url = site_url();
if(!$product){
header("Location: $site_url./404");
}

if(isset($_POST["add"])){

if ( isset($_COOKIE["cart"]) )
$cart = unserialize($_COOKIE["cart"]); // if cookie is set, get the contents of it
else
$cart = []; // else create an empty cart

// append new product and add to cart
$cart[$product["id"]] = [];
$cart[$product["id"]]["product_name"] = $product["name"];

setcookie("cart", serialize($cart), time()+3600);
$cart = unserialize($_COOKIE["cart"]);
dd($cart);
}

0 für die Antwort № 2

2. Teil der Frage: Wie kann die Bestellmenge eines Produktes erhöht werden:

    ...
// is this product alread in cart?
if ( isset($cart[$product["id"]])
$prod = $cart[$product["id"]]; // then pick it
else
{
// create a new product object
$prod = new stdClass();
// initialze with name and zer quantity
$prod->name = $product["name"];
$prod->quantity = 0;
}

// increment quantity
$prod->quantity ++;

// reassign to array
$cart[$product["id"]] = $prod;

...