PHP array data not updating - php

The assignment is to have a table display some products with an add to cart link which sends the user to another page which uses the information in the link to get the data to display the total of the purchase. The table is adding in new items that are clicked but not updating the actual quantity when an item is clicked more than once.
I have tried placing an echo in the check for the item already being in the cart and it does state the quantity of 1 before the quantity update and 2 after the update but for some reason this is not actually updating. The same goes for the price.
<?php
session_start();
if(empty($_SESSION['cart'])) {
$_SESSION['cart'] = array();
}
$cart = $_SESSION['cart'];
$id = $_GET['productid'];
$name = $_GET['productname'];
$price = $_GET['productprice'];
$qty = 1;
$alreadyHas = 0;
foreach($cart as $cartKey => $cartItem) {
if(!empty($cartItem['pid'])) {
if($cartItem['pid'] == $id) {
$cartItem['qty'] = $cartItem['qty'] + 1;
$cartItem['total'] = $cartItem['price'] * $cartItem['qty'];
$alreadyHas = 1;
}
}
}
if($alreadyHas == 0) {
$cartItem = array(
'pid' => $id,
'name' => $name,
'price' => $price,
'qty' => $qty,
'total' => $price
);
array_push($cart, $cartItem);
}
$_SESSION['cart'] = $cart;
?>

Your problem is in your foreach loop. You are updating $cartitem however because you are not passing it by reference in the loop the $cart variable itself is not being updated. Try changing the foreach loop to this (note the addition of & before `$cartItem):
foreach($cart as $cartKey => &$cartItem) {
Note that you could simplify your code with the use of array_search and array_column:
if (($k = array_search($id, array_column($cart, 'pid'))) !== false) {
$cart[$k]['qty'] = $cart[$k]['qty'] + 1;
$cart[$k]['total'] = $cart[$k]['price'] * $cart[$k]['qty'];
}
else {
$cartItem = array(
'pid' => $id,
'name' => $name,
'price' => $price,
'qty' => $qty,
'total' => $price
);
array_push($cart, $cartItem);
}

Related

PHP in_array not working after loop in session

I have a foreach loop to check all array of ID and if using in_array to see if any of the arrays of IDsis equaled my $_POST['id'] as shown below:
$cart = array (
'title' => $_POST['title'],
'price' => $_POST['price'],
'img_src' => $_POST['img_src'],
'id' => $_POST['id'],
);
foreach ($_SESSION['cart'] as $item) {
$id = $item['id'];
}
if(in_array($_POST['id'], $id)){
echo "ID exist";
}else{
$_SESSION['cart'][] = $cart;
$count = count($_SESSION["cart"]);
}
For some reason, it keeps adding even when the ID exist inside the list of arrays of IDs.
You are just changing the value of $id inside foreach loop. Try to store value in array. Refer the below code:
$cart = array (
'title' => $_POST['title'],
'price' => $_POST['price'],
'img_src' => $_POST['img_src'],
'id' => $_POST['id'],
);
$id = array();
foreach ($_SESSION['cart'] as $item) {
$id[] = $item['id'];
}
if(in_array($_POST['id'], $id)){
echo "ID exist";
}else{
$_SESSION['cart'][] = $cart;
$count = count($_SESSION["cart"]);
}

Checking for similar session variables and only increasing the quantity if one exists

I need to add items to my cart, so if I add one product of productid = 1, and then I add that same product of productid = 1, I need it to only increase the quantity of the item, and not add another session of that product.
I've tried the following:
foreach ($_SESSION['cart'] as $item) {
if ($item['product_id'] == $part_id) {
$quantity++;
}
}
But I need to know how to remove the previous added session for that product.
This is the code that I am using to add products to my cart currently, but the following just adds another product with the quantity 2, so I have:
// -- Cart -- //
Product : 1 Quantity : 1
Product : 1 Quantity : 2
// -- Cart -- //
Code:
foreach ($_SESSION['cart'] as $item) {
if ($item['product_id'] == $part_id) {
$quantity++;
}
}
$_SESSION['cart'][] = array(
'product_id' => $part_id,
'title' => $title,
'price' => $price,
'default_img' => $default_img,
'quantity' => $quantity);
EDIT: My initial question on how to unset the previous session, but if I add the same product another time, the quantity stays at 2, meaning it unsets the previous session with quantity = 3, and just increments the quantity +1 meaning the quantity remains at 2.
This worked for me :
$exists = false;
foreach ($_SESSION['cart'] as $key => $item) {
if ($item['product_id'] == $part_id) {
$exists = true;
}
}
if ($exists == true) {
$_SESSION["cart"][$key]['quantity']++;
}
else{
$_SESSION['cart'][] = array(
'product_id' => $part_id,
'title' => $title,
'price' => $price,
'default_img' => $default_img,
'quantity' => $quantity);
}
You are dealing with an associative array. You have the key to the object you want to remove. I would unset it right after adding the quantity. Now you can push your next object with the updated quantity.
foreach ($_SESSION['cart'] as $item) {
if ($item['product_id'] == $part_id) {
$quantity++;
$_SESSION['cart'][$part_id] == NULL //Add this
}
}

How can I add 1 to qty if In_array is true using PHP

I am trying to add 1 to session['cart']['qty'] if it's not a new entry and if it is a new item it will just add the item to session['cart'].
if (!isset($_SESSION['cart'])) {
$item = array('pid' => $p['productID'],
'qty' => 1
);
$_SESSION['cart'][0] = $item;
} else {
$item_id = array_column($_SESSION['cart'], "pid");
if (in_array($p['productID'], $item_id)) {
$to_update = 'qty';
$new_qty = 5;
$base = $_SESSION['cart']['pid']['qty'];
} else {
$count = count($_SESSION['cart']);
$item = array('pid' => $p['productID'],
'qty' => 1
);
$_SESSION['cart'][$count] = $item;
}
}
You could use the $pid as a unique index to track like
$pid=$p['productID'];
if(!isset($_SESSION['cart'][$pid])){
$item = array(
'pid' => $pid,
'qty' => 1
);
$_SESSION['cart'][$pid] = $item;
}else{
/*
* add 1 qty
*/
if(isset($_SESSION['cart'][$pid])) {
$_SESSION['cart'][$pid]['qty']= ($_SESSION['cart'][$pid]['qty'] +1);
}
}
you cal also use a similar reduce quantity.
You are not changing the session variable. Try this:
if (!isset($_SESSION['cart'])) {
$item = array('pid' => $p['productID'],
'qty' => 1
);
$_SESSION['cart'][0] = $item;
} else {
$item_id = array_column($_SESSION['cart'], "pid");
if (in_array($p['productID'], $item_id)) {
$new_qty = 5;
$_SESSION['cart'][$p['productID']]['qty'] += $new_qty;
} else {
$count = count($_SESSION['cart']);
$item = array('pid' => $p['productID'],
'qty' => 1
);
$_SESSION['cart'][$count] = $item;
}
}
This line here doesn't make sense.
$base = $_SESSION['cart']['pid']['qty'];
Multidimensional arrays don't work like that.
You are trying to access the key qty from the array $_SESSION['cart']['pid'], but that does not exist. Those two keys are siblings.

deleting and changing values in multidimensional array php

I've got the following code to remove 1 from the qty when a remove button is pressed and if the qty=1 the item will be removed from the array at the specific index.
for example if the first item in the array has an ID of '1B' and qty of '5' and name 'item1' second item in the array has the ID of '2B' and qty of '3' and name 'item2' and the remove button for this item is pressed, the qty will change to 2(as required) but the id will change to 1B and the name to 'item1'. The same thing happens if there are more than 2 products in the $_SESSION["Cart"] array.
I'm not sure where i'm going wrong, but this is my code:
code for $_SESSION["Cart"]
$_SESSION["Cart"] = array(
array(
'name' => "namehere",
'id' => "idHere",
'qty' => 1,
'price' => "pricehere"
)
//more arrays here
);
Code for Removing item
$prodID = $_GET["removeProd"];
foreach ($_SESSION["Cart"] as $cartItem) {
//only continue if qty is more than one
//remove item if 0 qty
if ($cartItem["id"] == $prodID) {
if ($cartItem["qty"] > 1) {
$qty = $cartItem["qty"] - 1; //decrease qty by one
$cart[] = array(
'name' => $cartItem["name"],
'id' => $cartItem["id"],
'qty' => $qty,
'price' => $cartItem["price"]
);
} //end if
} else {
$cart[] = array(
'name' => $cartItem["name"],
'id' => $cartItem["id"],
'qty' => $cartItem["qty"],
'price' => $cartItem["price"]
);
} //end else
$_SESSION["Cart"] = $cart;
} //end foreach
The problem is that you're assigning $_SESSION['Cart'] = $cart on each iteration, so it will only ever contain the last item in the $_SESSION['Cart'] array. If you move it below the end of the foreach your code should work.
You could simplify this a bit by passing $cartItem by reference. That way you only modify array elements which match $prodID:
foreach ($_SESSION['Cart'] as $key => &$cartItem) {
if ($cartItem['id'] == $prodID) {
if ($cartItem['qty'] > 1) {
$cartItem['qty'] -= 1;
} else {
unset($_SESSION['Cart'][$key]);
}
}
}
unset($cartItem); // break the binding
Your code has some algorhithmic/logic flaws. This code should do what you need it to do. Please try to find out what it actually does, and where are the flaws in your approach.
foreach ($_SESSION["Cart"] as $key=>$cartItem) {
//only continue if qty is more than one
//remove item if 0 qty
if ($cartItem["id"] == $prodID) {
if ($cartItem["qty"] > 1) {
$qty = $cartItem["qty"]--;// does the same thing as x = x - 1; //decrease qty by one
$cart[$key]['qty'] = $qty;
} //end if
else {
unset($cart[$key]);
}
break;// ends foreach loop ( assuming there can be only one item of the same type in the cart )
}
} //end foreach
$_SESSION["Cart"] = $cart;

Codeigniter update cart if product exists

How to update an item quantity if the product already exists in shopping cart?
Here's my add to cart function:
public function add() {
$product= $this->products_model->listProduct($this->input->post('id_product'));
$data = array(
'id' => $this->input->post('id_product'),
'qty' => $this->input->post('qty'),
'price' => $product->price,
'name' => $product->title );
$this->cart->insert($data);
redirect('product/'.$product->id.'/'.url_title($product->title, 'dash', TRUE));
}
With this function, if the product exists in the cart, let's say with quantity of 8, if i add the same product with quantity of 1 it'll be 1 and not 9.
Thanks in advance.
#AFRC
you can try
public function add() {
$flag = TRUE;
$dataTmp = $this->cart->contents();
foreach ($dataTmp as $item) {
if ($item['id'] == 'sku_123ABC') {
echo "Found Id so updatig quantity";
$qtyn = $item['qty'] + 1;
$this->update($item['rowid'], $qtyn);
$flag = FALSE;
break;
}
}
if ($flag) {
$data = array(
'id' => 'sku_123ABC',
'qty' => 1,
'price' => 39.95,
'name' => 'T-Shirt',
);
$this->cart->insert($data);
echo "Inserting as not found in the cart";
}
echo "Add1 called";
}
I don't see where $produto is defined, shouldn't it be, instead, $product->price and $product->title, respectively?
According to the docs :
Important: The first four array
indexes above (id, qty, price, and
name) are required. If you omit any of
them the data will not be saved to the
cart.
Be sure to check if they're acqually set (maybe look for spelling errors, like, I shoot in the dark, 'qtd' instead of 'qty', or something like that).
Moreover, if you want to UPDATE a product already present, you need to use $this->cart->update() instead of $this->cart->insert()
Just check with this if you have options
$rowid == md5($items['id'].implode('', $items['options']));
if not
$rowid == md5($items['id']);
use this code for add to cart
if (count($this->cart->contents())>0){
foreach ($this->cart->contents() as $item){
if ($item['id']==$product->id){
$data = array('rowid'=>$item['rowid'],'qty'=>++$item['qty']);
$this->cart->update($data);
}else{
$data = array('id'=>$product->id,'qty'=>1,'price'=>$product->price,'name'=>$product->id,'options'=>array('image'=>$product->thumb,'product_name'=>$product->title));
$this->cart->insert($data);
}
}
I used AFRC's answer to create the code below, it may be helpful. Thanks for your reply it really helped me! You can call the cart function below if there is an id present matching in your cart update will occur, otherwise insert will. It'll also display the cart view reguardless of insert, update, or just display. Please note i have a separate function get_specific_craft that is being used to get the slug items data (such as price and name).
public function cart($slug = "")
{
if($slug != "")
{
$craft = $this->crafts_model->get_specific_craft($slug);
$flag = TRUE;
foreach ($this->cart->contents() as $item)
{
if ($item['id'] == $slug)
{
$qtyn = $item['qty'] + 1;
$dat = array(
'rowid' => $item['rowid'],
'qty' => $qtyn
);
$this->cart->update($dat);
$flag = FALSE;
break;
}
}
if ($flag)
{
$crt = array(
'id' => $craft['id'],
'qty' => 1,
'price' => $craft['price'],
'name' => $craft['name']
//'options' => array('Size' => 'L', 'Color' => 'Red')
);
$this->cart->insert($crt);
}
}
$this->load->view('cart' , $this->data);
}

Categories