Page 1 of 1

Adding to shopping cart - cookie array

Posted: Wed Apr 07, 2010 10:17 am
by robbo82
Hi there

I'm new to PHP, but I need to build a basic script for a dummy shopping cart. I'll be using cookies for this and have done some search on arrays and cookies, but don't seem to be able to get anything working.

The code I have so far is:

Code: Select all

<?php 
$cart = (isset($_COOKIE['cart'])) ? unserialize(stripslashes($_COOKIE['cart'])) : array();

if(!$_POST['item'])
{
 echo "ERROR";
}
else
{
$item = $_POST['item'];
$cart[$item] = $item;
setcookie('cart[0]', serialize($cart),0,'','');
}
if (isset($_COOKIE['cart[0]']))
setcookie('cart[1]', serialize($cart),0,'','');
?>
And this stores the item selected on a previous page and I can display this item. However, I want to be able to add to this item so if they go back and select another, I can display all items in the cart.

I know it's something to do with cookies and arrays, but none of the examples I've tried work.

Any help is much appreciated.

Thanks in advance