php session update product if id already in the session - php

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
}

Related

Updating cookie values

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;
}

Add exactly 1 product to cart programmatically in Magento

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); }
}

Adjust Array Value in Shopping Cart based on User login state

How would I adjust individual values within the $_SESSION array depending on whether the user is logged_in or not logged_in. So basically the array values equate to the individual item prices within the shopping cart and will be adjusted if the user logs in or logs out of the SESSION.
Here's my current code:
PHP
if(!empty($_SESSION)){
foreach($_SESSION['basket'] as $b){
if ($session->logged_in) { $b['itemprice'] = ""; }
$sub_total = $b['itemprice'] * $b['itemqty'];
$total = $total + $sub_total;
// display contents of shopping cart
}
}
elseif (empty($_SESSION)) { ?>
// display message informing the user that their cart is empty
MYSQL
$itemids = array();
foreach ($_SESSION['basket'] as $item) {
$itemids[] = "'" . $item['itemid'] . "'";
}
$itemids_str = implode(',', $itemids);
$query = mysql_query("SELECT product_id, price, price_100 FROM product WHERE product_id IN ($itemids_str)");
while ($result=mysql_fetch_array($query)) { }
The closest I've come to getting this to work is each product in the cart is given the same price which changes if the user logs in or out. However, I need each item to change to the new price specific to that items product ID.
Some of our members receive a discount on certain items, so once the user logs in from being a GUEST to the registered USER the price needs to be changed on page refresh.
An example being :
**Logged in == FALSE**
Item 1 Price: 100.00
Item 2 Price: 100.00
**User logs in (Logged in == TRUE)**
Item 1 Price: 85.00
Item 2 Price: 94.00
I hope I've been clear - any advice would be appreciated.
Thanks
OPTION A:
function updateCartPrices()
{
$itemids = array();
foreach ($_SESSION['basket'] as $item) {
$itemids[] = "'" . $item['itemid'] . "'";
}
$itemids_str = implode(',', $itemids);
$query = mysql_query("SELECT product_id, price, price_100 FROM product WHERE product_id IN ($itemids_str)");
while ($result=mysql_fetch_array($query)) {
foreach ($_SESSION['basket'] as $key => $item)
{
if($result['product_id'] == $item['itemid'])
{
$_SESSION['basket'][$key]['itemprice'] = ($_SESSION['logged_in']) ? $result['price'] : $result['price_100'];
}
}
}
}
if(!empty($_SESSION)){
updateCartPrices();
foreach($_SESSION['basket'] as $b){
$sub_total = $b['itemprice'] * $b['itemqty'];
$total = $total + $sub_total;
// display contents of shopping cart
}
}
elseif (empty($_SESSION)) { ?>
// display message informing the user that their cart is empty
OPTION B (performance better):
function getLoggedInPrices()
{
$itemids = array();
foreach ($_SESSION['basket'] as $item) {
$itemids[] = "'" . $item['itemid'] . "'";
}
$itemids_str = implode(',', $itemids);
$query = mysql_query("SELECT product_id, price, price_100 FROM product WHERE product_id IN ($itemids_str)");
$prices = array();
while ($result=mysql_fetch_array($query)) {
$prices[$result['product_id']] = $result['price'];
}
return $prices;
}
if(!empty($_SESSION)){
$loggedInPrices = getLoggedInPrices();
foreach($_SESSION['basket'] as $b){
if($_SESSION['logged_in'])
{
$b['itemprice'] = $loggedInPrices[$b['itemid']];
}
$sub_total = $b['itemprice'] * $b['itemqty'];
$total = $total + $sub_total;
// display contents of shopping cart
}
}
elseif (empty($_SESSION)) {

php shopping cart unable to stop adding same product to cart array

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'];
}

Php add to shopping cart problem

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/');
}
}

Categories