Add to Cart Function
Posted: Thu Oct 02, 2008 4:50 pm
I am trying to create a shopping cart using session variables but I am having troubles.
Whenever a new item is added I check the basket array to see if the item key exists, if it does I simply increment the value. If it doesn't, then I add the new item to the cart array. The problem is once I add the first value to the array, the next key is always found for some reason and get incremented too.
Here is my code and function. Any ideas why it is not working correctly? Thanks.
Whenever a new item is added I check the basket array to see if the item key exists, if it does I simply increment the value. If it doesn't, then I add the new item to the cart array. The problem is once I add the first value to the array, the next key is always found for some reason and get incremented too.
Here is my code and function. Any ideas why it is not working correctly? Thanks.
Code: Select all
if ($_POST){
$itemID = $_POST['itemNumber'];
$itemName= $_POST['itemName'];
$itemPrice= $_POST['itemPrice'];
//add item to basket
add_to_cart($itemID, $itemName, $itemPrice);
}
function add_to_cart($id, $name, $price){
$BASKET = array(); //create empty basket
if (!empty($_SESSION['Basket'])) $BASKET = $_SESSION['Basket']; //restore basket if exists
if(array_key_exists($id, $BASKET)) { //check for item in basket
$BASKET[$id]["qty"] ++; //increment quantity
$_SESSION['Basket'] = $BASKET; //save basket in session
}else{
$BASKET[$id] = array ("name" => $name, "price" => $price, "qty" => 1);//place first item in basket
$_SESSION['Basket'] = $BASKET; //save basket in session
}
}