Mark Alan Mark Alan - 5 months ago 6x
PHP Question

Add to cart session not creating properly

I have created an add to cart functionality I am not pretty sure if I have developed perfectly or not.

when I am trying to add new session cart item it is not setting up for me the quantity, and

is inserting properly, but the other two options I am unable to store though like if i try to create a variable

it is working fine but when I try to add another session variable
it is not working

if(isset($_POST['cart'])) {
$pid = $_POST['product_id'];
$qty = $_POST['qty'];
$opt1 = $_POST['opt1'];
$opt2 = $_POST['opt2'];

if(isset($_SESSION['cart']['pid'][$pid])) {
$_SESSION['cart']['opt1'][$pid] = $opt1;
$_SESSION['cart']['opt2'][$pid] = $opt2;
if($qty > 1) {
$_SESSION['cart']['pid'][$pid] = $qty;
} else {
$_SESSION['cart']['pid'][$pid] = 1;
if($qty > 1) {
$_SESSION['cart']['pid'][$pid] = $qty;

<form method="POST" action="result.php">
<input type="text" name="product_id" placeholder="Product Id" />
<input type="text" name="qty" placeholder="Quantity" />
<input type="text" name="opt1" placeholder="A" />
<input type="text" name="opt2" placeholder="b" />
<input type="submit" name="cart" value="Add To Cart" />

Please let me know if I am on the right track and also the add to cart function is properly developed


I think you are confused, specially when you add an already-stored-in-session product:

When you already have the product_id in your cart, you write:

$_SESSION['cart']['pid'][$pid]++; you lost the product_id from your pid session index.

Maybe you should just add the quantity in another pid -> variable ... instead of changing the pid value.

if(isset($_POST['cart'])) {
    $pid  = $_POST['product_id'];
    $qty  = $_POST['qty'];
    $opt1 = $_POST['opt1'];
    $opt2 = $_POST['opt2'];

    // Create the prodcut_id array if it does not exist
    if(!isset($_SESSION['cart']['pid'][$pid])) {
        $_SESSION['cart']['pid'][$pid] = array();

    // Is the same item already stored? (same opt1 and opt2)
    $sameItem = false;

    if (!empty($_SESSION['cart']['pid'][$pid])) {
        foreach ($_SESSION['cart']['pid'][$pid] as $key => $product) {
             // Same options item?
             if ($product['opt1'] == $opt1 && 
                 $product['opt2'] == $opt2) {
                  $sameItem = $key;

    if ($sameItem !== false) {
        // Change the quantity
        $_SESSION['cart']['pid'][$pid][$sameItem]['qty'] += $qty;
    } else {
        // Store the item as new array key
               array('qty' => $qty, 'opt1' => $opt1, 'opt2' => $opt2);


By the way, are you using session_start() properly?