Magento: Is a certain product in the cart? - php

On my list.phtml page, I want my PHP script to be able to tell whether any product is in the cart, based on it's SKU.
So my conditional would theoretically be like this:
$_sku = 123;
if($_sku->isInBasket() == true){
echo 'Product: ' . $_sku . ' is in the cart';
}
How can this be achieved realistically?

Fetch all data from checkout session and check your product exits in Current session
$quote = Mage::getSingleton('checkout/session')->getQuote();
$foundInCart = false;
foreach($quote->getAllVisibleItems() as $item) {
if ($item->getData('sku') == $_sku) {
$foundInCart = true;
break;
}
}
it really bad to Check by sku.
Because of whenever configurable product cart then simple product sku in db.
So you need to check using product id.for this case you need find the id of $sku by Mage::getModel('catalog')->loadBySku($sku); before start of products foreach loop.
$_skuPId='';
$matchPro=Mage::getModel('catalog')->loadBySku($sku);
if($matchPro->getId()){
$_skuPId=$matchPro->getId();
}
$quote = Mage::getSingleton('checkout/session')->getQuote();
$foundInCart = false;
foreach($quote->getAllVisibleItems() as $item) {
if ($item->getData('prodduct_id') == $_skuPId) {
$foundInCart = true;
break;
}
}

Related

i want to increase cart quantity php every time add to cart is clicked. I checked few provided solutions but none of them worked

<?php
session_start();
if (isset($_GET) & !empty($_GET)) {
$id = $_GET['id'];
$url = $_GET['sourceurl'];
if (isset($_GET['quant']) & !empty($_GET['quant'])) {
$quant = $_GET['quant'];
} else {
$quant = 1;
}
$_SESSION['cart'][$id] = array("quantity" => $quant);
//header('location:' . $url);
//header('location:index.php?message=1');
} else {
//header('location:' . $url);
}
echo "<pre>";
print_r($_SESSION['cart']);
echo "</pre>";
I have common php page addtocart.php to add product directly to cart from homepage and also from single.php where user can add quantity. If quantity is not given(i.e adding to cart from index page) quantity is directly set to 1. Here I want to increase quanity every time user clicks on addtocart. Above is the code of addtocart.php
Replace $_SESSION['cart'][$id] = array("quantity" => $quant); for this oneliner.
$_SESSION['cart'][$id]['quantity'] = ((isset($_SESSION['cart'][$id]['quantity'])) && ($_SESSION['cart'][$id]['quantity'] > 0)) ? ++$_SESSION['cart'][$id]['quantity'] : $quant;

Prevent duplicate items being added to cart in PHP

I'm using a session array to store products in a cart.
If the selected product is already in the cart, instead of the product being added again, I want to display a message informing the user that the product has already been added.
I've tried looping through the array to find the matching key. I've also tried the in_array($var1,$var2) function. With these, the status tells the user their product is already in the cart but adds the product anyway.
The last thing I tried was the array_search function to check if the key exists but the product is still getting added to the cart regardless.
if(isset($_GET['productID']) && $_GET['productID'] != "") {
$product = $_GET['productID'];
$product = (string)$product;
$result_product = GetSpecificProduct($product);
if(!empty($result_product)) {
$cart_array[$result_product['ProductID']] = array(
'ProductID'=>$result_product['ProductID'],
'ProductName'=>$result_product['ProductName'],
'Price'=>$result_product['Price'],
'Specifications'=>$result_product['Specifications'],
'CO'=>$result_product['CO'],
'CatID'=>$result_product['CatID'],
'Name'=>$result_product['Name'],
'Quantity'=>1
);
}
if(empty($_SESSION['tocoto_cart'])){
$_SESSION['tocoto_cart'] = $cart_array;
$status = $result_product['ProductName']." added to your cart.";
}else if(!empty($_SESSION['tocoto_cart'])) {
$key = array_search($result_product['ProductID'],$_SESSION['tocoto_cart']);
if($key !== false) {
$status = "Selected product is already in your cart.";
} else {
$status = $result_product['ProductName'] . " added to your cart.";
$_SESSION['tocoto_cart'] = array_merge($_SESSION['tocoto_cart'],$cart_array );
}
try to do something like this
$array = $_SESSION['tocoto_cart'];
$key = array_search($result_product['ProductID'], array_column($array, 'ProductID'));
if($key !== false) {
$status = "Selected product is already in your cart.";
} else {
$status = $result_product['ProductName'] . " added to your cart.";
$_SESSION['tocoto_cart'] = array_merge( $_SESSION['tocoto_cart'], $cart_array );
}
Bad approach to store cart items in session, because when server (or php-fpm/apache process) restarts, all carts will be cleared with the sessions.
Store cart items in DB, and to be sure that item is unique within the single cart use combined unique constraint on user_token, cart_id and item_id with ON DUPLICATE KEY UPDATE quantity = quantity + 1 SQL
If this is too complex for you, try to modify this piece of your code
$key = array_search($result_product['ProductID'],$_SESSION['tocoto_cart']);
if($key !== false) {
to
if (array_key_exists($result_product['ProductID'],$_SESSION['tocoto_cart'])) {
$_SESSION['tocoto_cart'][$result_product['ProductID']]['Quantity'] += 1;
}

Add the same idProduct to SESSION in cart php

I´m making a cart in php that get the data of the products from a MySQL Database.
The problem is: I can´t add the same product to the SESSION.
I need that, because the user may want one product with a picture and another one with another picture;
I need that so much.
This is the code I'm using to add the item to the cart:
if(isset($_GET['action'])){
//ADD TO THE CART
if($_GET['action'] == 'add'){
$id = intval($_GET['idProduct']);
if(!isset($_SESSION['cart'][$id])){
$_SESSION['cart'][$id] = 1;
}else{
$_SESSION['cart'][$id] += 1;
}
}
//UPDATE CART
if($_GET['action'] == 'up'){
if(is_array($_POST['prod'])){
foreach($_POST['prod'] as $id => $qtd){
$id = intval($id);
$qtd = intval($qtd);
if(!empty($qtd) || $qtd <> 0){
$_SESSION['cart'][$id] = $qtd;
}else{
unset($_SESSION['cart'][$id]);
}
}
}
}
I don't know how to add the same product. I tried using an Array and getting the KEY from it, but I didn't know how to use it;

foreach only checks first value in array, then creates new value

I'm working on a php shopping cart and I'm trying to have the cart update the quantity of the item, rather than creating new entries for the same item. However when entering a product that is already in the cart, my foreach statement only checks it against the first array value and then creates a new entry for that product.
Can someone please help me work through this and figure out why it's not checking against the whole array list?
Here's my update method:
function CheckForExistingEntry($id, $setOf, $quantity) {
// if the product ID and the SET OF is equal in multiple products, update the quanity instead of making new records
foreach ($_SESSION['shopping_cart'] as $key => $product) {
if ($id == $product['product_id'] && $setOf == $product['setOf']) {
// Update Cart Value
$_SESSION['shopping_cart'][$key]['quantity'] += $quantity;
$_SESSION['shopping_cart'][$key]['price'] *= $_SESSION['shopping_cart'][$key]['quantity'];
break;
} else {
// Add New Cart Value
AddToCart($id, $setOf, $quantity);
break;
}
}
}
You have a break; in both if and else, which means that it will always break after the first iteration.
Let's remove the else-block, since we just want to continue to the next item if it wasn't found.
Try this: (I've commented the changes):
// Define a variable that holds the state.
$updated = false;
foreach ($_SESSION['shopping_cart'] as $key => $product) {
if ($id == $product['product_id'] && $setOf == $product['setOf']) {
// Update Cart Value
$_SESSION['shopping_cart'][$key]['quantity'] += $quantity;
$_SESSION['shopping_cart'][$key]['price'] *= $_SESSION['shopping_cart'][$key]['quantity'];
// Set updated as true and break the loop
$updated = true;
break;
}
}
if (!$updated) {
// We didn't update any items, add a new item instead
AddToCart($id, $setOf, $quantity);
}

Displaying items from a php session shopping cart

I am writing a shopping cart and so far have set up a session using this:
<?php
session_start();
if (!isset($_SESSION['cart']))
{
$_SESSION['cart'] = array();
}
?>
The elements added to the cart are all keys to a database (image_id). I'm just wanting to display each individual image_id along with the option to remove it from the cart.
At the moment I have one function which displays the total number of elements
function writeShoppingCart() {
$cart = $_SESSION['cart'];
if (!$cart) {
return '<p>0</p>';
} else {
// Parse the cart session variable
$items = explode(',',$cart);
$s = (count($items) > 1) ? 's':'';
return '<p>'.count($items).'</p>';
}
}
I'd just love some advice on how to show the actual image_id's
Many thanks

Categories