Jump to content

Update Quantity value in a Session Array


toyfruit

Recommended Posts

Hi all. I'm a noob with PHP and need some help with a shopping cart I'm working on.

Basically I am using a session to keep 'added' items in my cart. Which seems to be working OK. What I now want to do is store a quantity with each item (so I can then update it).

 

I'm having trouble working out how to do this. I need to be able to identify and set the quantity against the item in the array. My code is below - this updates a value 'qty' but this value is not linked to a specific item and I can't work out how to do it. I am starting a session in an include, so its there I just haven't included it here.

 

<?php 
// get the id from the url
$id = $_GET['id'];
$cat_id = $_GET['cat_id'];

// check if an array has been set up for the items, if not set one up
if (!isset($_SESSION['cart']) || !is_array($_SESSION['cart'])) {
$_SESSION['cart'] = array();
} 

// don't add anything to the array if the value is NULL
if ($id != NULL){
// check if the item being added is already in the array, if not add it
if (in_array($id, $_SESSION['cart'])) {
    	echo "This item is already in your basket <br /><br />";
// although the value is in the array, update the quantity by one
$_SESSION['cart']['qty'] ++;
} else {
// otherwise add the item to the array and set its initial value to 1
	array_push($_SESSION['cart'], $id);
	$_SESSION['cart']['qty'] = 1;
}
}



// display the names of all the items in the basket (key = index number, value = name of the item)
foreach ($_SESSION['cart'] as $key => $value){
$result = mysql_query("SELECT * FROM image WHERE id = $value", $connection);
while ($row = mysql_fetch_array($result)){
	// show the name of the image
	echo $row["img_name"] . "<br />";
	// show the image
	echo "<img src='images/thb/" . $row["img_name"] . "' /><br />";
	// show the quantity
	echo $_SESSION['cart']['qty'];
}	
}

?>

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.