I am storing a Shopping Cart in a PHP Session and then loading it to show the items in the cart.
The issue is that currently, I am seeing each of the items without consolidation, meaning if an item is added 2 times in the cart, it will be shown twice.
How could I consolidate the results by itemId?
if(is_array($_SESSION['cart']))
{
$max=count($_SESSION['cart']);
for($i=0;$i<$max;$i++)
{
$pid=$_SESSION['cart'][$i]['itemId'];
$q=$_SESSION['cart'][$i]['qty'];
if($q==0) continue;
$query2 = $con -> prepare("SELECT * FROM item_descr WHERE id_item = :idItem");
$query2-> bindValue (':idItem',$pid);
$query2->execute();
$row2 = $query2->fetch(PDO::FETCH_ASSOC);
?>
<div class="checkoutItems">
<span class='itemNameChck'><?php echo $row2['name']; ?> </a></span>
<span class="itemQtyChck"><?php echo $row2['price']; ?> </span>
<span class="itemQtyChck"><?php echo $q; ?> </span>
<span class="itemQtyChck"><?php $totalPerItem = $q * $row2['price']; echo $totalPerItem; ?> </span>
</div>
<?php
}
}
Here is how I add the items to the cart:
function addtocart($pid,$q)
{
if($pid<1 or $q<1) return;
if(is_array($_SESSION['cart']))
{
$max=count($_SESSION['cart']);
$_SESSION['cart'][$max]['itemId']=$pid;
$_SESSION['cart'][$max]['qty']=$q;
$max=count($_SESSION['cart']);
}
else
{
$_SESSION['cart']=array();
$_SESSION['cart'][0]['itemId']=$pid;
$_SESSION['cart'][0]['qty']=$q;
$max=count($_SESSION['cart']);
}
//}
}
In my opinion – you have to get rid of that ID that contains cart item index.
Just put
itemIdthere, and before you add item – check if this element of array is set.You wrote this code, that adds new element to array everytime, and now you want to consolidate. It makes no sense for me. Add new element only when you have to. Otherwise, just update quantity.
In my opinion your cart should look like this:
Then, when adding item you can check if cart item with that itemid contains any elements.
This is just a draft/idea, but I hope it will help you.