Issue with Unset (PHP)

Viewed 249

I am trying to unset an item from session array, it unset once then brings back again. for exg :-

if i click to remove itemId = 5, it removes from session array, then i click to remove itemId = 6, then i see the old itemId = 5 is back in array again.

/*** delete item from cart ***/

       public function deleteCartItem($id, $customerId, $cartId, $wishlistFlag=false) // Param: ProductID, CustomerID, CartID, WishlistFlag
        {
            $conn = $_SESSION['conn'];
            $itemId = false;
            $chk = array();
           
                    $sql = "DELETE FROM cart_items WHERE product_id=? AND cart_id=?";
                    $stmt = mysqli_prepare($conn, $sql);//$result = $conn->query($sql);
                    $stmt->bind_param('ii', $item['id'],$cartId);
                    $stmt->execute();
                    $itemId = $i;
                    echo $itemId; 
                    $chk[] = $_SESSION['cart'];
                    echo'</br>'; 
                    print_r($chk);
                }
            }
            if (isset($_SESSION['cart'][$itemId])){
                unset($_SESSION['cart'][$itemId]);
       }    
} 





<?php

    $_SESSION['cart'] = array (
  0 => 
  array (
    'id' => 6154353459,
    'name' => 'pro one Night Out Mesh Tee',
    'display_brand' => 'Widow',
    'qty' => 1,
    'price' => '28.0000',
    'special_price' => 0,
    'rule_price' => '',
    'attributes' => 
    array (
      0 => 'BLACK',
      1 => 'XX-Large',
    ),
    'option80' => 18,
    'option125' => 3457,
    'child_product_id' => 61535897,
    'giftcard' => '',
    'whole_preorder' => 0,
    'preorder_shipping_date' => NULL,
    'available_qty' => 5,
    'isRefundable' => true,
    'max_sale_qty' => false,
    'isFree' => 0,
    'segment' => 
    array (
      'magento_product_id' => '65315459',
      'product_id' => 'P19335935',
      'quantity' => 1,
      'name' => 'pro one Night Out Mesh Tee',
      'brand' => 'Widow',
      'price' => 28.0,
      'special_price' => NULL,
      'regular_price' => 28.0,
      'size_type' => 'Regular',
      'manufacturer' => 'Widow',
      'trend' => 'WID goodie Hour 2020',
      'microcategory' => 'Mesh Shirt',
      'doll_category' => NULL,
      'stock_quantity' => 10,
      'sku' => 'S493660',
      'child_stock_quantity' => 1,
      'size' => 'XX-Large',
      'swatch' => 'BLACK',
    ),
  ),
  5 => 
  array (
    'id' => 615345465,
    'name' => 'pro one Night Out Mesh Leggings',
    'display_brand' => 'Widow',
    'qty' => 1,
    'price' => '30.0000',
    'special_price' => 0,
    'rule_price' => '',
    'attributes' => 
    array (
      0 => 'BLACK',
      1 => 'Medium',
    ),
    'option80' => 18,
    'option125' => 3454,
    'child_product_id' => 6315890,
    'giftcard' => '',
    'whole_preorder' => '',
    'preorder_shipping_date' => NULL,
    'available_qty' => 37,
    'isRefundable' => true,
    'max_sale_qty' => false,
    'isFree' => 0,
    'segment' => 
    array (
      'magento_product_id' => '64334515465',
      'product_id' => 'P193936',
      'quantity' => 1,
      'name' => 'pro one Night Out Mesh Leggings',
      'brand' => 'Widow',
      'price' => 30.0,
      'special_price' => NULL,
      'regular_price' => 30.0,
      'size_type' => 'Regular',
      'manufacturer' => 'Widow',
      'trend' => 'WID goodie Hour 2020',
      'microcategory' => 'Printed Leggings',
      'doll_category' => NULL,
      'stock_quantity' => 10,
      'sku' => 'S493664',
      'child_stock_quantity' => 10,
      'size' => 'Medium',
      'swatch' => 'BLACK',
    ),
  ),
  2 => 
  array (
    'id' => 615445348,
    'name' => 'pro two My Lashes Sunglasses',
    'display_brand' => '',
    'qty' => 1,
    'price' => '15.0000',
    'special_price' => 0,
    'rule_price' => '',
    'attributes' => 
    array (
      0 => 'BLACK',
      1 => 'ONE SIZE',
    ),
    'option80' => 18,
    'option125' => 6212,
    'child_product_id' => 6154345358,
    'giftcard' => '',
    'whole_preorder' => '',
    'preorder_shipping_date' => NULL,
    'available_qty' => 295,
    'isRefundable' => true,
    'max_sale_qty' => false,
    'isFree' => 0,
    'segment' => 
    array (
      'magento_product_id' => '6153453448',
      'product_id' => 'P19645642180',
      'quantity' => 1,
      'name' => 'pro two My Lashes Sunglasses',
      'brand' => '',
      'price' => 15.0,
      'special_price' => NULL,
      'regular_price' => 15.0,
      'size_type' => 'Regular',
      'manufacturer' => 'CIEL',
      'trend' => 'WID goodie Hour 2020',
      'microcategory' => 'Cat Eye Sunglasses',
      'category' => 'Accessories,Sunglasses,Cat Eye Sunglasses',
      'special_category' => 'What\'s New,Char Test Category,Widow',
      'doll_category' => NULL,
      'stock_quantity' => 10,
      'sku' => 'S486477',
      'child_stock_quantity' => 10,
      'size' => 'ONE SIZE',
      'swatch' => 'BLACK',
    ),
  ),
  3 => 
  array (
    'id' => 61465645461,
    'name' => 'pro one Night Out goodie Dress',
    'display_brand' => 'Widow',
    'qty' => 1,
    'price' => '45.0000',
    'special_price' => 0,
    'rule_price' => '',
    'attributes' => 
    array (
      0 => 'BLACK',
      1 => 'X-Large',
    ),
    'option80' => 18,
    'option125' => 3456,
    'giftcard' => '',
    'whole_preorder' => '',
    'preorder_shipping_date' => NULL,
    'available_qty' => 12,
    'isRefundable' => true,
    'max_sale_qty' => false,
    'isFree' => 0,
    'segment' => 
    array (
      'magento_product_id' => '616465461',
      'product_id' => 'P1935446934',
      'quantity' => 1,
      'name' => 'pro one Night Out goodie Dress',
      'brand' => 'Widow',
      'price' => 45.0,
      'special_price' => NULL,
      'regular_price' => 45.0,
      'size_type' => 'Regular',
      'manufacturer' => 'Widow',
      'trend' => 'WID goodie Hour 2020',
      'microcategory' => 'goodie Dresses',
      'category' => 'Clothing,Dresses,Mini,goodie Dresses',
      'special_category' => 'Brandsgoodie,Char Test Category,Widow,Widow',
      'doll_category' => NULL,
      'stock_quantity' => 10,
      'sku' => 'S493652',
      'child_stock_quantity' => 10,
      'size' => 'X-Large',
      'swatch' => 'BLACK',
    ),
  ),
  4 => 
  array (
    'id' => 6154566225,
    'name' => 'Feelings Maxi Dress',
    'display_brand' => 'Widow',
    'qty' => 1,
    'price' => '58.0000',
    'special_price' => 0,
    'rule_price' => '',
    'attributes' => 
    array (
      0 => 'BLACK',
      1 => 'Large',
    ),
    'option80' => 18,
    'option125' => 3455,
    'child_product_id' => 61456455677,
    'giftcard' => '',
    'whole_preorder' => '',
    'preorder_shipping_date' => NULL,
    'available_qty' => 30,
    'isRefundable' => true,
    'max_sale_qty' => false,
    'isFree' => 0,
    'segment' => 
    array (
      'magento_product_id' => '614565225',
      'product_id' => 'P1945652050',
      'quantity' => 1,
      'name' => 'Phantom Feelings Maxi Dress',
      'brand' => 'Widow',
      'price' => 58.0,
      'special_price' => NULL,
      'regular_price' => 58.0,
      'size_type' => 'Regular',
      'manufacturer' => 'Widow',
      'trend' => 'WID goodie Hour 2020',
      'microcategory' => 'Maxi Dresses',
      'category' => 'Dresses,Midi & Maxi,Maxi Dresses',
      'special_category' => 'Brandsgoodie,Char Test Category,Widow,Widow',
      'doll_category' => NULL,
      'stock_quantity' => 10,
      'sku' => 'S485794',
      'child_stock_quantity' => 10,
      'size' => 'Large',
      'swatch' => 'BLACK',
    ),
  )
  );

$itemId = 5; // comes dybamically;
   if (   isset($_SESSION['cart'][$itemId])) {
            unset($_SESSION['cart'][$itemId]);
    }
?>

I am not getting it, Any thoughts ?

You can also take a look at the sandbox- http://sandbox.onlinephpfunctions.com/code/6bab394d1da39a301ce82b974022da7b7efaface

Please refer to the whole code here - PHP SESSION UPDATE ISSUE

Thankyou

5 Answers

You're proably re-reading session-data so that deletion you're making is overridden.

<?php
$cart = $_SESSION['cart'];
unset($cart[5]);
echo 'deletion confirmed';

//later in execution..
//accidental re-read of cart from session-variable.
//BAD CODE STARTS HERE
$cart = $_SESSION['cart']; //error since you're re-reading cart from session.
//BAD CODE END
//calc totals in basket or something..
$totals = 0;
foreach($cart as $item) {
  $totals = $totals + $item['qty'] * $item['price'];
}

//somewhere in the script, the session variable is updated.
$_SESSION['cart'] = $cart;

GOOD TO KNOW PHP passes most variables by value as default, meaning that

$cart = $_SESSION['cart'];

copies the content of $_SESSION['cart'] into $cart.

Any change made to $cart will not automatically be updated in $_SESSION['cart'].

If you don't want a copy but a reference, you may use:

$cart = &$_SESSION['cart'];

and you will not need to save $cart into $_SESSION.

(Just make sure $_SESSION['cart'] is initialized when making the reference)

** AND **

Session variables tend to grow to a mess.. Use getters and setters in your application.

The best approach is to after unset get the updated array from session and declare it again

$cart_array = array (
    0 => 
    array (
        'id' => 6154353459,
        'name' => 'pro one Night Out Mesh Tee',
        'display_brand' => 'Widow',
        'qty' => 1,
        'price' => '28.0000',
        'special_price' => 0,
        'rule_price' => '',
        'attributes' => 
        array (
        0 => 'BLACK',
        1 => 'XX-Large',
        ),
        'option80' => 18,
        'option125' => 3457,
        'child_product_id' => 61535897,
        'giftcard' => '',
        'whole_preorder' => 0,
        'preorder_shipping_date' => NULL,
        'available_qty' => 5,
        'isRefundable' => true,
        'max_sale_qty' => false,
        'isFree' => 0,
        'segment' => 
        array (
        'magento_product_id' => '65315459',
        'product_id' => 'P19335935',
        'quantity' => 1,
        'name' => 'pro one Night Out Mesh Tee',
        'brand' => 'Widow',
        'price' => 28.0,
        'special_price' => NULL,
        'regular_price' => 28.0,
        'size_type' => 'Regular',
        'manufacturer' => 'Widow',
        'trend' => 'WID goodie Hour 2020',
        'microcategory' => 'Mesh Shirt',
        'doll_category' => NULL,
        'stock_quantity' => 10,
        'sku' => 'S493660',
        'child_stock_quantity' => 1,
        'size' => 'XX-Large',
        'swatch' => 'BLACK',
        ),
    ),
    5 => 
    array (
        'id' => 615345465,
        'name' => 'pro one Night Out Mesh Leggings',
        'display_brand' => 'Widow',
        'qty' => 1,
        'price' => '30.0000',
        'special_price' => 0,
        'rule_price' => '',
        'attributes' => 
        array (
        0 => 'BLACK',
        1 => 'Medium',
        ),
        'option80' => 18,
        'option125' => 3454,
        'child_product_id' => 6315890,
        'giftcard' => '',
        'whole_preorder' => '',
        'preorder_shipping_date' => NULL,
        'available_qty' => 37,
        'isRefundable' => true,
        'max_sale_qty' => false,
        'isFree' => 0,
        'segment' => 
        array (
        'magento_product_id' => '64334515465',
        'product_id' => 'P193936',
        'quantity' => 1,
        'name' => 'pro one Night Out Mesh Leggings',
        'brand' => 'Widow',
        'price' => 30.0,
        'special_price' => NULL,
        'regular_price' => 30.0,
        'size_type' => 'Regular',
        'manufacturer' => 'Widow',
        'trend' => 'WID goodie Hour 2020',
        'microcategory' => 'Printed Leggings',
        'doll_category' => NULL,
        'stock_quantity' => 10,
        'sku' => 'S493664',
        'child_stock_quantity' => 10,
        'size' => 'Medium',
        'swatch' => 'BLACK',
        ),
    ),
    2 => 
    array (
        'id' => 615445348,
        'name' => 'pro two My Lashes Sunglasses',
        'display_brand' => '',
        'qty' => 1,
        'price' => '15.0000',
        'special_price' => 0,
        'rule_price' => '',
        'attributes' => 
        array (
        0 => 'BLACK',
        1 => 'ONE SIZE',
        ),
        'option80' => 18,
        'option125' => 6212,
        'child_product_id' => 6154345358,
        'giftcard' => '',
        'whole_preorder' => '',
        'preorder_shipping_date' => NULL,
        'available_qty' => 295,
        'isRefundable' => true,
        'max_sale_qty' => false,
        'isFree' => 0,
        'segment' => 
        array (
        'magento_product_id' => '6153453448',
        'product_id' => 'P19645642180',
        'quantity' => 1,
        'name' => 'pro two My Lashes Sunglasses',
        'brand' => '',
        'price' => 15.0,
        'special_price' => NULL,
        'regular_price' => 15.0,
        'size_type' => 'Regular',
        'manufacturer' => 'CIEL',
        'trend' => 'WID goodie Hour 2020',
        'microcategory' => 'Cat Eye Sunglasses',
        'category' => 'Accessories,Sunglasses,Cat Eye Sunglasses',
        'special_category' => 'What\'s New,Char Test Category,Widow',
        'doll_category' => NULL,
        'stock_quantity' => 10,
        'sku' => 'S486477',
        'child_stock_quantity' => 10,
        'size' => 'ONE SIZE',
        'swatch' => 'BLACK',
        ),
    ),
    3 => 
    array (
        'id' => 61465645461,
        'name' => 'pro one Night Out goodie Dress',
        'display_brand' => 'Widow',
        'qty' => 1,
        'price' => '45.0000',
        'special_price' => 0,
        'rule_price' => '',
        'attributes' => 
        array (
        0 => 'BLACK',
        1 => 'X-Large',
        ),
        'option80' => 18,
        'option125' => 3456,
        'giftcard' => '',
        'whole_preorder' => '',
        'preorder_shipping_date' => NULL,
        'available_qty' => 12,
        'isRefundable' => true,
        'max_sale_qty' => false,
        'isFree' => 0,
        'segment' => 
        array (
        'magento_product_id' => '616465461',
        'product_id' => 'P1935446934',
        'quantity' => 1,
        'name' => 'pro one Night Out goodie Dress',
        'brand' => 'Widow',
        'price' => 45.0,
        'special_price' => NULL,
        'regular_price' => 45.0,
        'size_type' => 'Regular',
        'manufacturer' => 'Widow',
        'trend' => 'WID goodie Hour 2020',
        'microcategory' => 'goodie Dresses',
        'category' => 'Clothing,Dresses,Mini,goodie Dresses',
        'special_category' => 'Brandsgoodie,Char Test Category,Widow,Widow',
        'doll_category' => NULL,
        'stock_quantity' => 10,
        'sku' => 'S493652',
        'child_stock_quantity' => 10,
        'size' => 'X-Large',
        'swatch' => 'BLACK',
        ),
    ),
    4 => 
    array (
        'id' => 6154566225,
        'name' => 'Feelings Maxi Dress',
        'display_brand' => 'Widow',
        'qty' => 1,
        'price' => '58.0000',
        'special_price' => 0,
        'rule_price' => '',
        'attributes' => 
        array (
        0 => 'BLACK',
        1 => 'Large',
        ),
        'option80' => 18,
        'option125' => 3455,
        'child_product_id' => 61456455677,
        'giftcard' => '',
        'whole_preorder' => '',
        'preorder_shipping_date' => NULL,
        'available_qty' => 30,
        'isRefundable' => true,
        'max_sale_qty' => false,
        'isFree' => 0,
        'segment' => 
        array (
        'magento_product_id' => '614565225',
        'product_id' => 'P1945652050',
        'quantity' => 1,
        'name' => 'Phantom Feelings Maxi Dress',
        'brand' => 'Widow',
        'price' => 58.0,
        'special_price' => NULL,
        'regular_price' => 58.0,
        'size_type' => 'Regular',
        'manufacturer' => 'Widow',
        'trend' => 'WID goodie Hour 2020',
        'microcategory' => 'Maxi Dresses',
        'category' => 'Dresses,Midi & Maxi,Maxi Dresses',
        'special_category' => 'Brandsgoodie,Char Test Category,Widow,Widow',
        'doll_category' => NULL,
        'stock_quantity' => 10,
        'sku' => 'S485794',
        'child_stock_quantity' => 10,
        'size' => 'Large',
        'swatch' => 'BLACK',
        ),
    )
    );

if(!isset($_SESSION['cart'])) {
    $_SESSION['cart'] = $cart_array;
} else {
    $_SESSION['cart'] = (array) $_SESSION['cart'];
}

$itemId = 3;

if (isset($_SESSION['cart'][$itemId])) {
    unset($_SESSION['cart'][$itemId]);
}

print_r($_SESSION['cart']);

Now it will be not back the remove item again, unless if you destroy the session

Why is there $item['id'] used in $stmt->bind_param( (instead of $id?). $item is not a parameter of the function.

Similarly, where does the variable $i come from in $itemId = $i;?

I have written a simplified version of your problem and it works as expected. It uses a form and buttons to give the array indices to the PHP script. If you have a different setup (like using Ajax) you need to clarify that.

session_start();

if (!isset($_SESSION['cart']) || sizeof($_SESSION['cart']) === 0)
 {
  echo('Resetting cart.' . PHP_EOL);
  $_SESSION['cart'] = [0 =>'zero', 1 =>'one', 2 =>'two', 3 =>'three', 4 =>'four'];
 }

echo('<pre>before ' . print_r($_SESSION['cart'], TRUE) . '</pre>');

$itemId = isset($_GET['itemid']) ? $_GET['itemid'] : FALSE;
if ($itemId !== FALSE)
 {
  if (isset($_SESSION['cart'][$itemId]))
   {
    echo('Unsetting &raquo;' . $itemId . '&laquo;.' . PHP_EOL);
    unset($_SESSION['cart'][$itemId]);
   }
  else
    echo('&raquo;' . $itemId . '&laquo; not in cart.' . PHP_EOL);
 }
else
  echo('No item ID given.' . PHP_EOL);

echo('<pre>after ' . print_r($_SESSION['cart'], TRUE) . '</pre>');

echo('<form method="get" action="' . $_SERVER['PHP_SELF'] . '">' . PHP_EOL);
foreach ($_SESSION['cart'] as $key=>$value)
  echo('<button name="itemid" value="' . $key .  '">' . $value . '</button>' . PHP_EOL);
echo('</form>' . PHP_EOL);

The manual has made it clear

If a globalized variable is unset() inside of a function, only the local variable is destroyed. The variable in the calling environment will retain the same value as before unset() was called.

To unset() a global variable inside of a function, then use the $GLOBALS array to do so:

<?php
function foo() 
{
    unset($GLOBALS['bar']);
}

$bar = "something";
foo();
?>
$stmt->bind_param('ii', $item['id'],$cartId);
$stmt->execute();

where is $item['id'] from?

Try using different variable names on your bind_param and declare their value before query execute() method.

Related