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;
Related
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;
}
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;
...
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
}
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'];
}
This is the link to the site on test domain Domain Link
The problem im having is removing an item from the cart. everything works on my local host but as soon as i uploaded it to live server the remove item from cart stoped working. Can someone please tell me where im going wrong. thanks team.
<?php
include_once("../php/cart_config.php");
session_start();
//add item in shopping cart
if(isset($_POST["type"]) && $_POST["type"]=='add')
{
$product_code = filter_var($_POST["product_code"], FILTER_SANITIZE_STRING); //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'=>1, '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
$qty = $cart_itm["qty"]+1; //increase the quantity
$product[] = array('name'=>$cart_itm["name"], 'code'=>$cart_itm["code"], 'qty'=>$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 exist in the list
//continue only if quantity is more than 1
//removing item that has 0 qty
if($cart_itm["qty"]>1)
{
$qty = $cart_itm["qty"]-1; //just decrese the quantity
//prepare array for the products session
$product[] = array('name'=>$cart_itm["name"], 'code'=>$cart_itm["code"], 'qty'=>$qty, 'price'=>$cart_itm["price"]);
}
}else{
$product[] = array('name'=>$cart_itm["name"], 'code'=>$cart_itm["code"], 'qty'=>$cart_itm["qty"], 'price'=>$cart_itm["price"]);
}
//set session with new array values
$_SESSION["products"] = $product;
}
//redirect back to original page
header('Location:'.$return_url);
}
?>
PHP header can not be output if HTML is already displayed. You could use Javascript instead.
?>
<script type="text/javascript">
window.location = "<?php echo $return_url; ?>";
</script>
<?php
This wil do the same, but it will always work!