incrementing session variable name


Hi all - hoping somebody can see this clearer than me…

Goal: to create a very simple shopping cart page that receives $_POST info and stores it as an array in a session variable so items will be displayed in cart on clients return to shopping cart page.

Problem: I can get the array to display the first item that I add to the shopping cart but each susequest item just overwrites the first because it is using the same session variable name. How do I store the next product info in a DIFFERENT session variable and display it on the shopping cart page without writing over the first?

I have two pages with products on them which need to submit orders to the shopping cart page. They use a simple form with these fields:

This is what I have so far on the cartaction page which can display the first product added to the cart:

<?php //If form is submitted, call the function and save all data into the array $_SESSION['form'] if($_POST['submit'] == "Buy"){ setSessionVars(); } function setSessionVars() { if ( !isset($_SESSION['cart']) ) $_SESSION['cart'] = array(); $item = array(); foreach($_POST as $fieldname => $fieldvalue) { $item[$fieldname] = $fieldvalue; } $_SESSION['cart'] = $item; echo "
" .'<img src="images/'.$item['item'].'.jpg"' . " " . $item['item'] . " " . ' ' . "
"; } ?>

I am new to PHP and have hit a brick wall as to how to display each product array as a new session variable in the shopping cart. I would like to keep it as simple as possible as I am getting easily confused! Is there a way that I can increment the session variable with something like this:

<?php //session counter $counter = count($_SESSION['cart']); if (($_POST['name'] !="")){ $counter = $counter + 1; $_SESSION['cart'][$counter] = array(); } ?>

Or can I pass a field as a product ID and use this somehow to create a new session variable for each product or clear the post variables somehow?

Any help would be much appreciated.



Well, there are tons of ways to do anything. In this case it depends how you want to handle your transactions.
If you just want to keep a running “cart”, it is easy. You just have to remember that any ( ANY ) session variable is just a variable. So, you can create a session variable that is an array. You could create a session variable and
call it $_SESSION[‘cart’] and make it an array. It works like any other array. A simple version is like this:
$_SESSION[‘array’] = array(‘foo’ => ‘bar’, 0, 1, 2, 3, ‘abc’ => ‘xyz’);
$_SESSION[‘array’][‘abc’] = ‘xyz123’;

Soooo, you could just create a “cart” array and keep it as a session variable. The only issue with this is that you do not want to store tons of items in it as it may cause issues going from page to page and you should empty the array once is is posted as an order and entered into the database. (Using UNSET’ing the cart variable.)

So, hope that is what you are asking. Good luck…