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.
Thanks