Adding to shopping cart - cookie array

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
robbo82
Forum Newbie
Posts: 1
Joined: Wed Apr 07, 2010 10:02 am

Adding to shopping cart - cookie array

Post 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
Post Reply