code snippets that implement the suggestions -
<?php
session_start();
// simple form process controller -
$action = isset($_POST['action']) ? $_POST['action'] : '';
switch($action){
case 'add':
// add/increment item to cart (quantity one)
// inputs: 'add to cart' flag, item id
// processing: add new or increment existing item id in the cart
$id = (int)$_POST['id'];
if($id > 0){ // valid submitted id
if(!isset($_SESSION['item'][$id])){ // not already in cart
$_SESSION['item'][$id] = 0; // create entry
}
$_SESSION['item'][$id]++; // increment quantity
}
break;
case 'delete':
// delete item from cart
// inputs: 'delete from cart' flag, item id
// processing: remove item id entry from the cart
$id = (int)$_POST['id'];
if($id > 0){ // valid submitted id
unset($_SESSION['item'][$id]);
}
break;
}
// display the cart
if(empty($_SESSION['item'])){
echo "Your cart is empty!<br>";
} else {
echo "Your cart has ".array_sum($_SESSION['item'])." item(s) in it.<br>";
// get the item ids from the cart
$ids = implode(',',array_keys($_SESSION['item']));
echo "ids are: $ids<br>";
// code to get and display the product infomration for the list of ids is left as a programming exercise
}
// display what's going on
echo '<pre>','cart:',print_r($_SESSION,true),'post:',print_r($_POST,true),'</pre>';
?>
Add some items -<br>
id: 123<form method='post' action=''>
<input type='hidden' name='action' value='add'>
<input type='hidden' name='id' value='123'>
<input type='submit' value='Add to cart'>
</form>
id: 456<form method='post' action=''>
<input type='hidden' name='action' value='add'>
<input type='hidden' name='id' value='456'>
<input type='submit' value='Add to cart'>
</form>
Delete some items -<br>
id: 123<form method='post' action=''>
<input type='hidden' name='action' value='delete'>
<input type='hidden' name='id' value='123'>
<input type='submit' value='Remove from cart'>
</form>
id: 456<form method='post' action=''>
<input type='hidden' name='action' value='delete'>
<input type='hidden' name='id' value='456'>
<input type='submit' value='Remove from cart'>
</form>