Page 1 of 1

Add to Cart Function

Posted: Thu Oct 02, 2008 4:50 pm
by kristolklp
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.

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

Re: Add to Cart Function

Posted: Thu Oct 02, 2008 6:04 pm
by Stryks
Interesting ... it looks like it should really be working.

Perhaps try changing ...

Code: Select all

   $BASKET = array(); //create empty basket
    if (!empty($_SESSION['Basket'])) $BASKET = $_SESSION['Basket']; //restore basket if exists
 
// to
    if(isset(!_SESSION['Basket'])) $BASKET = $_SESSION['Basket']; else $BASKET = array();
... also ...

Code: Select all

if(array_key_exists($id, $BASKET)) {    //check for item in basket
 
// could be
 
if(isset($BASKET[$id])) {    //check for item in basket
I'd also recommend ...

Code: Select all

if($_SERVER['REQUEST_METHOD'] == 'POST') {
 
// instead of
 
if ($_POST){
That last is not going to be your problem ... just an observation.

It does seem odd though. I cant see any specific reason why it would increment all items.

How are you calling add_to_cart? In a loop? Can we see that if the problem is still happening?

Cheers

Re: Add to Cart Function

Posted: Thu Oct 02, 2008 8:48 pm
by kristolklp
I figured out that the problem is not in the code for the basket but somewhere between the communication between flash posting the variables and php reading them from the server. I made a simple html page to post the variables instead and everything worked fine.

I implemented your recommendations anyhow!

Thanks for the response.