Saving drop Down menu value in session

Currenly working on making a shopping cart. I want to make a drop down menu that hold values of shirt sizes and when you click add to cart it takes the value of the shirt size and saves it with the item I’d. So when the user goes to there cart they see something like “shirt name - large”

I’m having trouble trying to save the drop down value in the session so any example will truly help!!

Thanks for any help

How would I display the options on the cart page?

thank you for replying.

The add cart function is

function addtocart ($pid,$q) {
If(is_array($_SESSION[‘cart’])) {
If(product_exists($pid)) return;
$max=count($_SESSION[‘cart’]);
$_SESSION[‘cart’][$max][‘id’]=$pid;
$_SESSION[‘cart’][$max][‘qty’]=$q;
}
else {
$_SESSION[‘cart’]=array();
$_SESSION[‘cart’][0][‘id’]=$pid;
$_SESSION[‘cart’][0][‘qty’]=$q;
}

And the code on the product page is

If(($add == ‘add’) && ($productid > 0)) {
$pid=$productid;
addtocart($pid,1);
header(‘location:/product/myshoppingcart’);
exit();
}

Sorry I didn’t put it in the code tags I’m writting this from my phone.


<select name="shirt_size">
   <option value="s">small</option>
   <option value="m">medium</option>
   <option value="l">large</option>
</select>


//Process form
$_POST['shirt_size'] //will be the value from the select (s, m or l)

How is the other cart contents stored? In the session? If so add the size in the same way.

Ok I figured it out thank you very much!

So $_SESSION[‘cart’] is an array of items with id and qty keys. You just need to add a ‘size’ key, or maybe an options sub array if there are different types of options you might want to store. Add another argument to addtocart() to receive that data too.


function addtocart($pid, $q, $options = array()) {
	if(!isset($_SESSION['cart'])) {
		$_SESSION['cart'] = array();
	}
	if(product_exists($pid)) {
		return;
	}
		
	$_SESSION['cart'][] = array(
		'id' => $pid,
		'qty' => $q,
		'options' => $options
	);
}

There’s no need for the branching logic to see if it’s the first, or subsequent items, or to use $max to append to the array. Just use the empty square brackets to create a new element regardless.

Then when displaying the cart you’ll look at $_SESSION[‘cart’][123][‘options’] for an array of extra options like size, colour, or whatever else you might put in there.