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;
}
Related
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
}
Using Magento 1.8.1, on the checkout page, I'm trying to add a product to the cart in the code. Here is the code I'm using:
$totals = Mage::getSingleton('checkout/cart')->getQuote()->getTotals();
$subtotal = $totals["subtotal"]->getValue();
$free_samples_prod_id = 1285;
if ( $subtotal >= 50 ) {
$this->addProduct($free_samples_prod_id, 1);
}
else{
$cartHelper = Mage::helper('checkout/cart');
$items = $cartHelper->getCart()->getItems();
foreach ($items as $item) {
if ($item->getProduct()->getId() == $free_samples_prod_id) {
$itemId = $item->getItemId();
$cartHelper->getCart()->removeItem($itemId)->save();
break;
}
}
}
The code is in: app\code\core\Mage\Checkout\Model\Cart.php under public function init()
The product does get added sucessfully, however, everytime somebody visits their cart page, the quantity increases by one. How can I modify that code so the quantity is always 1?
Thank you
Axel makes a very good point, but to answer your immediate question, why not test for the product's presence before you add it
$cartHelper = Mage::helper('checkout/cart');
$items = $cartHelper->getCart()->getItems();
$subtotal = $totals["subtotal"]->getValue();
$free_samples_prod_id = 1285;
if ( $subtotal >= 50 ) {
$alreadyAdded = false;
foreach ($items as $item) {
if($item->getId() == $free_samples_prod_id) { $alreadyAdded = true; break; }
}
if(!$alreadyAdded) { $this->addProduct($free_samples_prod_id, 1); }
}
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'];
}
Im trying to create a php function that adds an item to a shopping cart. what i want it to do is check the array to see if the item is already in there, if it is increase the quantity, if not create the item in the cart.
What it is doing instead is it adding an item, it'll work the first time (if the items already there it'l just increase the quantity) but if you add another item it keeps on creating new instances of that item in the shopping cart
e.g
item 1 - quantity 4
item 2 - quantity 1
item 2 - quantity 1
item 2 - quantity 1... and so on...
below is the code i have so far?
function add_item ($id, $qty)
{
$count=$this->countItems;
echo "uytfdgghjkl;kj<br>";
$added = false;
if($count>0)
{
$i=0;
while($added == false)
{
echo "fghjkl<br>";
$tid = $this->items[$i]->getId();
echo "new ID: ".$tid."<br>";
echo "old ID: ".$id."<br>";
echo $i;
if($tid == $id)
{
$amount = $this->items[$i]->getQty();
$this->items[$i]->setQty($amount+1);
$added = true;
//$i++;
//break;
}
if($added == true)
{
break;
}
else //if($added == false)
{
$this->items[$this->countItems] = new OrderItem($id, $qty);
//$this->total = $total+ ($qty *$price);
$this->countItems++;
$added = true;
//break;
}
//else break;
$i++;
}
}
else
{
$this->items[$this->countItems] = new OrderItem($id, $qty);
//$this->total = $total+ ($qty *$price);
$this->countItems++;
}
}
The problem is that you aren't searching the whole array first to see if the item is present in it. The code below should work, but I may have made a typo or something else so make sure you double check it.
function add_item ($id, $qty)
{
$count=$this->countItems;
echo "uytfdgghjkl;kj<br>";
$added = false;
if($count>0)
{
for($i=0; $i < $count; $i++)
{
echo "fghjkl<br>";
$tid = $this->items[$i]->getId();
echo "new ID: ".$tid."<br>";
echo "old ID: ".$id."<br>";
echo $i;
if($tid == $id)
{
$amount = $this->items[$i]->getQty();
$this->items[$i]->setQty($amount+1);
$added = true;
break;
}
}
}
if(!$added)
{
$this->items[$this->countItems] = new OrderItem($id, $qty);
//$this->total = $total+ ($qty *$price);
$this->countItems++;
}
}
An even better option would be to use a dictionary
ie.
$arr = array();
$arr['item_id'] = new OrderItem(...);
Then you can check if the item is in the array using:
if(isset($arr[$id])){
...
}
The logic is flawed. The code will increment the item's quantity only if it happens to be the first item in the cart. Otherwise, it will add the item. Evidenced here:
if($added == true) // if this cart item's quantity was incremented
{
break;
}
else // add item
{
$this->items[$this->countItems] = new OrderItem($id, $qty);
// etc...
}
Instead, you should remove the new OrderItem($id, $qty) from the loop and check the value of $added after looping through all the cart items. For this to work, you need to loop via for (instead of a while) using $count.
class Products extends CI_Controller{
function __construct(){
parent::__construct();
// Load cart library
$this->load->library('cart');
// Load product model
$this->load->model('product');
}
function index(){
$data = array();
// Fetch products from the database
$data['products'] = $this->product->getRows();
// Load the product list view
$this->load->view('products/index', $data);
}
function addToCart($proID){
// Fetch specific product by ID
$product = $this->product->getRows($proID);
// Add product to the cart
$data = array(
'id' => $product['id'],
'qty' => 1,
'price' => $product['price'],
'name' => $product['name'],
'image' => $product['image']
);
$this->cart->insert($data);
// Redirect to the cart page
redirect('cart/');
}
}