Hey,
I am just finishing off my shopping cart however i have stumbled upon a problem.
When i add to basket i execute the following method:
public function AddToCart(){
!isset($_SESSION['ID']) ? $_SESSION['ID'] = array() : '';
!isset($_SESSION['theName']) ? $_SESSION['theName'] = array() : '';
!isset($_SESSION['quantity']) ? $_SESSION['quantity'] = array() : '';
!isset($_SESSION['price']) ? $_SESSION['price'] = array() : '';
!isset($_SESSION['image']) ? $_SESSION['image'] = array() : '';
array_push($_SESSION['ID'], $_POST['ID']);
array_push($_SESSION['theName'], $_POST['theName']);
array_push($_SESSION['quantity'], $_POST['quantity']);
array_push($_SESSION['price'], $_POST['price']);
array_push($_SESSION['image'], $_POST['image']);
$loc = $_SERVER['HTTP_REFERER'];
echo "<script>window.location.href='".$loc."'</script>";
}
This creates the session as an array. Now lets say i click on the add to basket button twice for the same item. I don’t want to have 2 instances of the same item which is what i have not, but i want to have the item name once and then ‘x2’ next to the quantity.
So moving on on my items page i have hidden input values which populates the basket session, shown below:
<input type="hidden" name="ID" value="<?php echo $row['theID']; ?>" />
<input type="hidden" name="theName" value="<?php echo $row['theName']; ?>" />
<input type="hidden" name="price" value="<?php echo $row['price']; ?>" />
<input type="hidden" name="image" value="<?php echo $row['image']; ?>" />
<input type="hidden" name="quantity" value="1" />
Now what i have managed to do is when my basket is empty and i add an item to the basket multiple times the basket works exactly how i want. However when i then add a different item to the basket more than once it adds a quantity to both items.
This is because i need to target the specific item in the basket.
if(isset($_POST['ID'])){
if(!empty($_SESSION['theName'])){
$i=0;
foreach($_SESSION['theName'] as $name){
if($_POST['theName'] == $name){
$_SESSION['quantity'][$i] = $_SESSION['quantity'][$i] + 1;
}else {
$cart->AddToCart();
}
}
}
}
I tested this code and clicked add to cart multiple times on 2 different items. I get this:
Dior - £69.99 x4
CK Top - £1.99 x1
CK Top - £1.99 x1
Now this item:
Dior - £69.99 x4
was actually x3 but when i clicked on a different item more than once it updated both items quantities.
So my question is, can i target a specific item in a session array and accomplish what i am trying to do?
I would really appreciate if you can help me out.
Thanks