I'm saving a cart array within a cookie, to send it to the shopping cart page. Whenever i go to a page from another product and click on add to cart it doesn't add it to the array, but seems to overwrite it.
$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);
}
You have given the answer already: you are overwriting the cart each time this script runs. Changes:
$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);
}
2nd part of the question: How to increase order quantity of a product:
...
// 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;
...
Related
When added from a third-party product to the cart. I want to change the quantity of goods in the basket. Get alert Product (........ ) is over.
if(is_array($arCartPrice)){
//if($arCartPrice['OPTIONS']['MINIMUM']>1){$QUANTITY=$arCartPrice['OPTIONS']['MINIMUM'];}else{$QUANTITY=1;}
$QUANTITY=$arCartPrice['AVAILABLE_NUM'];
$DefaultCategory = 12;
$DefaultTaxGroup = 0;
$Price = $arCartPrice['PRICE_CONVERTED'];
$PriceVAT = round($Price);
$Reference = $arCartPrice['ARTICLE'].' / '.$arCartPrice['BRAND'];
//Presta init
global $context;
if(!$context){$context = Context::getContext();}
$logged = $context->cookie->__get('logged');
$id_cart = $context->cookie->__get('id_cart');
$id_lang = $context->cookie->__get('id_lang');
$id_guest = $context->cookie->__get('id_guest');
$id_currency = $context->cookie->__get('id_currency');
// Add cart if no cart found
if (!$id_cart){
$context->cart = new Cart();
$context->cart->id_customer = $context->customer->id;
$context->cart->id_currency = $id_currency;
$context->cart->add();
if($context->cart->id){
$context->cookie->id_cart = (int)$context->cart->id;
}
$id_cart = (int)$context->cart->id;
}
$doAdd="Y";
//if(!$logged>0){$doAdd="N"; $TCore->arErrorMessages[] = 'You must be logged in to buy products';}
//if(trim($Reference)=='' OR !$Price>0 OR !$QUANTITY>0){$doAdd="N"; $TCore->arErrorMessages[] = 'Add to cart data is missing!';}
if(!$id_cart>0){$doAdd="N"; ErAdd("Your cookie <b>id_cart</b> is wrong!",1);}
if(!$id_lang>0){$doAdd="N"; ErAdd("Your cookie <b>id_lang</b> is wrong!",1);}
if($doAdd!="N"){
//Check avail. tecdoc item in Presta
$sql = 'SELECT p.`id_product`, pl.`name` FROM `'._DB_PREFIX_.'product` p
LEFT JOIN `'._DB_PREFIX_.'product_lang` pl ON (p.`id_product` = pl.`id_product`)
WHERE pl.`id_lang` = '.$id_lang.' AND
p.`price` = '.$Price.' AND
p.`reference` = "'.$Reference.'"
';
$arRes = Db::getInstance()->executeS($sql);
if(count($arRes)>0){
$NewTID = $arRes[0]['id_product'];
}else{
//Supplier data (for 1C integration)
$supplierName = $arCartPrice['SUPPLIER_STOCK'];
$supplierId = $suppliers = (Supplier::getIdByName($supplierName));
if (!$supplierId) {
$supplier = new Supplier();
$supplier->name = $supplierName;
$supplier->active = 1;
$supplier->add();
$supplierId = $supplier->id;
}
$obProduct = new Product(false,false,$id_lang);
$obProduct->id_category_default = $DefaultCategory;
$obProduct->unity = $arCartPrice['ADD_URL'];
$obProduct->name = $arCartPrice['ARTICLE'] .' / '.substr($arCartPrice['NAME'],0,400).' / '.$arCartPrice['BRAND'];
$obProduct->description = 'This product is created automatically by ';
$obProduct->description_short = $arCartPrice['SUPPLIER_STOCK'].' ['.$arCartPrice['DAY'].' days]';
$obProduct->price = $Price;
$obProduct->wholesale_price = $arCartPrice['PRICE'];
$obProduct->reference = $Reference;
$obProduct->link_rewrite = $arCartPrice['CPID'];
$obProduct->available_for_order = 1; //true
$obProduct->visibility = 'none';
$obProduct->is_virtual = 0;
//$obProduct->weight = round($arCartPrice['OPTIONS']['WEIGHT']/1000,2);
$obProduct->minimal_quantity = 1;
$obProduct->condition = 'used';
$obProduct->condition = 'refurbished';
$obProduct->available_now = $arCartPrice['AVAILABLE_NUM'];
$obProduct->quantity = $arCartPrice['AVAILABLE_NUM'];
//supplier
$obProduct->supplier_name = $supplierName;
$obProduct->id_supplier = $supplierId;
$obProduct->id_tax_rules_group = $DefaultTaxGroup;
//echo '<br><pre>';print_r($obProduct);echo '</pre>';die();
$obProduct->add();
if($obProduct->id>0){
$NewTID = $obProduct->id;
$obProduct->setWsCategories(Array(Array("id"=>$DefaultCategory)));
//Add image
if($arCartPrice['IMG_SRC']!='' AND $NewTID>0){
$shops = Shop::getShops(true, null, true);
$image = new Image();
$image->id_product = $NewTID;
$image->position = Image::getHighestPosition($NewTID)+1;
$image->cover = true; // or false;
if(($image->validateFields(false, true)) === true && ($image->validateFieldsLang(false, true)) === true && $image->add()){
$image->associateTo($shops);
$tmpfile = tempnam(_PS_TMP_IMG_DIR_, 'ps_import');
if(Tools::copy($arCartPrice['IMG_SRC'], $tmpfile)){
$path = $image->getPathForCreation();
ImageManager::resize($tmpfile, $path.'.jpg');
}
unlink($tmpfile);
}
}
}else{
ErAdd("Prestashop new Item ID is false",1);
}
unset($obProduct);
}
if($NewTID>0){
//if($arCartPrice['AVAILABLE']>0){StockAvailable::setQuantity($NewTID, false, $arCartPrice['AVAILABLE']);}
StockAvailable::setQuantity($NewTID, 0, (int) $arCartPrice['AVAILABLE']);
$obCart = new Cart($id_cart);
$obCart->id_lang = $id_lang;
$obCart->id_currency = $id_currency;
if($obCart->updateQty((int)$QUANTITY=1, (int)$NewTID)){
Header('Location: http://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']); die();
}else{
ErAdd(" Add to Cart is false. NewTID=".$NewTID,1);
}
How to fix the code so you can update the quantity of goods in your cart.
And the number of 10 pieces. 1 piece is added to the cart. I want to add more to my cart. How to implement it? When I add 2 pieces. I receive a message Product (........ ) is over..
enter image description here
First of all, after you created the product, check in the Backoffice if the quantity is well stored (If the newly created product quantity is equal with $arCartPrice['AVAILABLE_NUM'] )
Maybe you can try with enabled "Allow ordering when out of stock" .
I have a shopping cart using cookies, you can add products to it by going to the product-detail page and click on add cart. The script needs to add +1 to the quantity in the shopping cart, everytime you can click on add. I don't know why, but the quantity stays 1 everytime.
Basically, the question is: Why doesn't it update the quantity within the cookie?
Product.php:
if(isset($_POST['add'])){
if(!empty($_POST['m'])){
if (isset($_COOKIE['cart'])){
$cart = json_decode($_COOKIE['cart'], TRUE, 512, JSON_OBJECT_AS_ARRAY); // 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']]['m'] = empty($_POST['m']) ? 1 : $_POST['m'];
if(!empty($cart[$product['id']]['quantity'])){
$cart[$product['id']]['quantity'] += 1;
} else {
$cart[$product['id']]['quantity'] = 1;
}
setcookie('cart', json_encode($cart), time()+3600, '/');
} else {
$error = "U moet minimaal 1m invullen";
}
}
Also in the shopping cart itself, i need to be able to modify the quantity, this value is allowed to be overwritten.
shoppingcart.php:
if(isset($_COOKIE['cart'])){
$cart = json_decode($_COOKIE['cart'], TRUE, 512, JSON_OBJECT_AS_ARRAY);
} else {
$cart = [];
}
// dd($cart);
if(isset($_POST['remove'])){
unset($cart[$_POST['item']]);
setcookie('cart', json_encode($cart), time()+3600, '/');
}
$list = $model->selectMultipleById($cart, 'carpet');
Try this:
// append new product and add to cart
//first test if you have the id in your cookie. if so: update qty +1
if(!empty($cart[$product['id']])){
$cart[$product['id']]['quantity'] += 1;
}
//else create a new item in the cookie
else {
$cart[$product['id']] = [];
$cart[$product['id']]['quantity'] = 1;
}
//now $cart[$product['id']]['m'] always exists, so you can update m
$cart[$product['id']]['m'] = empty($_POST['m']) ? 1 : $_POST['m'];
This is what i tried but i seem to repeat myself with my code.
if(isset($_COOKIE['cart'][$product['id']])){
$cart[$product['id']]['m'] = empty($_POST['m']) ? 1 : $_POST['m'];
if(!empty($cart[$product['id']]['quantity'])){
$cart[$product['id']]['quantity'] += 1;
} else {
$cart[$product['id']]['quantity'] = 1;
}
} else {
$cart[$product['id']] = [];
$cart[$product['id']]['m'] = empty($_POST['m']) ? 1 : $_POST['m'];
$cart[$product['id']]['quantity'] = 1;
}
The following function is on carts page, after a user has added product from previous product page. The problem is I need the multidimensional array just to update quantity in cart for same product code being added.
Can someone help me add an if statement so when the same productcode is added quantity increases?
Like this answer however my add to cart is different. PHP Sessions shopping cart: update product if it's already id the session
function AddToCart()
{
$cart = isset($_SESSION['cart']) ? $_SESSION['cart'] : '';
$itemcount = isset($_SESSION
['itemcount']) ? $_SESSION['itemcount'] : 0;
{
$i = array_search($_POST['productcode'], $cart[PRODUCTCODE]);
$cart[PRODUCTCODE] [$itemcount] = $_POST['productcode'];
$cart[PRODUCTNAME] [$itemcount] = $_POST['productname'];
$cart[QUANTITY][$itemcount] = intval($_POST['quantity']);
$cart[PRICE][$itemcount] = $_POST['price'];
$itemcount = $itemcount + 1;
if(strlen($error) == 0) {
$_SESSION['cart'] = $cart;
$_SESSION['itemcount'] = $itemcount;
}
return $error;
}
Try this.
//check for an existing match
$found = FALSE;
if($cart){
$idx = 0;
foreach($cart[PRODUCTCODE] as $idx => $product){
if($product == $_POST['productcode']){
$found = TRUE;
break;
}
}
}
//if we found a match
if($found){
$cart[QUANTITY][$idx] += intval($_POST['quantity']);
}
//otherwise add new item
else{
//your other code here
}
When i use this add to cart script i erases the already added quantity in session!
But i want it to add the specefied quantity plus the quantity already in basket session.
How to do that?
Scroll to the right on demo (the page i F****d up)//
Live DEMO here http://www.sanwebe.com/assets/php-shopping-cart/index.php
Here is the following code that i use
<?php
session_start();
include_once("config.php");
//empty cart by distroying current session
if(isset($_GET["emptycart"]) && $_GET["emptycart"]==1)
{
$return_url = base64_decode($_GET["return_url"]); //return url
session_destroy();
header('Location:'.$return_url);
}
//add item in shopping cart
if(isset($_POST["type"]) && $_POST["type"]=='add')
{
$product_code = filter_var($_POST["product_code"], FILTER_SANITIZE_STRING); //product code
$product_qty = filter_var($_POST["product_qty"], FILTER_SANITIZE_NUMBER_INT); //product code
$return_url = base64_decode($_POST["return_url"]); //return url
//MySqli query - get details of item from db using product code
$results = $mysqli->query("SELECT product_name,price FROM products WHERE product_code='$product_code' LIMIT 1");
$obj = $results->fetch_object();
if ($results) { //we have the product info
//prepare array for the session variable
$new_product = array(array('name'=>$obj->product_name, 'code'=>$product_code, 'qty'=>$product_qty, 'price'=>$obj->price));
if(isset($_SESSION["products"])) //if we have the session
{
$found = false; //set found item to false
foreach ($_SESSION["products"] as $cart_itm) //loop through session array
{
if($cart_itm["code"] == $product_code){ //the item exist in array
$product[] = array('name'=>$cart_itm["name"], 'code'=>$cart_itm["code"], 'qty'=>$product_qty, 'price'=>$cart_itm["price"]);
$found = true;
}else{
//item doesn't exist in the list, just retrive old info and prepare array for session var
$product[] = array('name'=>$cart_itm["name"], 'code'=>$cart_itm["code"], 'qty'=>$cart_itm["qty"], 'price'=>$cart_itm["price"]);
}
}
if($found == false) //we didn't find item in array
{
//add new user item in array
$_SESSION["products"] = array_merge($product, $new_product);
}else{
//found user item in array list, and increased the quantity
$_SESSION["products"] = $product;
}
}else{
//create a new session var if does not exist
$_SESSION["products"] = $new_product;
}
}
//redirect back to original page
header('Location:'.$return_url);
}
//remove item from shopping cart
if(isset($_GET["removep"]) && isset($_GET["return_url"]) && isset($_SESSION["products"]))
{
$product_code = $_GET["removep"]; //get the product code to remove
$return_url = base64_decode($_GET["return_url"]); //get return url
foreach ($_SESSION["products"] as $cart_itm) //loop through session array var
{
if($cart_itm["code"]!=$product_code){ //item does,t exist in the list
$product[] = array('name'=>$cart_itm["name"], 'code'=>$cart_itm["code"], 'qty'=>$cart_itm["qty"], 'price'=>$cart_itm["price"]);
}
//create a new product list for cart
$_SESSION["products"] = $product;
}
//redirect back to original page
header('Location:'.$return_url);
}
?>
Maybe Change
This:
//found user item in array list, and increased the quantity
$_SESSION["products"] = $product;
To:
//found user item in array list, and increased the quantity
$_SESSION["products"] = $_SESSION["products"] + $product;
This is just a picture of the result I got. As you can see, item 4 can be added again and again. What I want in my shopping cart is that, for each color, item 4 can only be added once.
if( isset($_SESSION['cart']) ){
################## Do looping to check array cart if already has item with same id and color ##########################
$i = 0;
$j = 1; // set to index [1] //
$found = '';
foreach( $_SESSION['cart'] as $cart ){
######## Check if product chosen already exist in the cart #######
if( $cart[$i]['id'] == $new_product['id'] && $cart[$i]['color'] == $new_product['color'] ){
$found = true; // Found existing item in the array cart //
}
else{
$found = false;
$j++; // No item found in array cart, increase to index [2] //
}
####### If no same item is found in cart, add the new product to the cart array ###############
$i++; // Increase array index to check second array and so on //
}
if(!$found){ // No item found in array cart, add item into cart //
$_SESSION['cart'][$j]['id'] = $new_product['id'];
$_SESSION['cart'][$j]['product_name'] = $new_product['product_name'];
$_SESSION['cart'][$j]['discount'] = $new_product['discount'];
$_SESSION['cart'][$j]['qty'] = $new_product['qty'];
$_SESSION['cart'][$j]['color'] = $new_product['color'];
$_SESSION['cart'][$j]['shipping_fee'] = $new_product['shipping_fee'];
}
}
else{
$_SESSION['cart'][0]['id'] = $product['id'];
$_SESSION['cart'][0]['product_name'] = $product['product_name'];
$_SESSION['cart'][0]['discount'] = $product['discount'];
$_SESSION['cart'][0]['qty'] = $qty;
$_SESSION['cart'][0]['color'] = $color;
$_SESSION['cart'][0]['shipping_fee'] = $shipping_fee;
}
How could I have my codes changed?
try this ...
if($found){ // item found in array cart
$_SESSION['cart'][0]['id'] = $product['id'];
$_SESSION['cart'][0]['product_name'] = $product['product_name'];
$_SESSION['cart'][0]['discount'] = $product['discount'];
$_SESSION['cart'][0]['qty'] = $qty;
$_SESSION['cart'][0]['color'] = $color;
$_SESSION['cart'][0]['shipping_fee'] = $shipping_fee;
}
}
else{ // no item found
$_SESSION['cart'][$j]['id'] = $new_product['id'];
$_SESSION['cart'][$j]['product_name'] = $new_product['product_name'];
$_SESSION['cart'][$j]['discount'] = $new_product['discount'];
$_SESSION['cart'][$j]['qty'] = $new_product['qty'];
$_SESSION['cart'][$j]['color'] = $new_product['color'];
$_SESSION['cart'][$j]['shipping_fee'] = $new_product['shipping_fee'];
}