Jump to content

Add to Cart Function


kristolklp

Recommended Posts

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.  For example, theI  first item added will have a qty of 1 but when I add item2 it will start with a qty of 2, and item1 qty will now be 2.  Below is my code, any ideas?  TIA!

 

<?php
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){980
$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"] += 1; //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
	}
}
?>

Link to comment
https://forums.phpfreaks.com/topic/126524-add-to-cart-function/
Share on other sites

below is how i am checking the array:

 

if (!empty($_SESSION['Basket'])) {
foreach ( (array) $_SESSION['Basket'] as $key => $value){
	echo "Item Number= ".$key." Item Name= ".$_SESSION['Basket'][$key]["name"]." Item Price= ".$_SESSION['Basket'][$key]["price"]." Quantity= ".$_SESSION['Basket'][$key]["qty"]."</td></tr><br>";
}

 

Any ideas on this problem would be greatly appreciated.  Thanks.

Link to comment
https://forums.phpfreaks.com/topic/126524-add-to-cart-function/#findComment-655179
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.