[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now

x
?
Solved

How to delete a value in a session array?

Posted on 2011-05-01
24
Medium Priority
?
480 Views
Last Modified: 2012-05-11
Hi, I am trying to delete an product in my shopping cart:

function removeItem() {
      if((isset($_POST['delete'])) && (isset($_POST['item']))) {
            $item = $_POST['item'];
            $cart = $_SESSION['cart'];
            empty($cart[$item]);
      }
}

but its not working.  Any ideas?
0
Comment
Question by:FairyBusiness
  • 9
  • 5
  • 4
  • +3
24 Comments
 
LVL 36

Expert Comment

by:Loganathan Natarajan
ID: 35502614
try with unset();
function removeItem() {
      if((isset($_POST['delete'])) && (isset($_POST['item']))) {
            $item = $_POST['item'];
            $cart = $_SESSION['cart'];
            unset($cart[$item]);
      }
}

Open in new window

0
 
LVL 36

Expert Comment

by:Loganathan Natarajan
ID: 35502622
You did not store the item into the session ??  

are you trying to empty the item variable ..? if so , do like this,

unset($item);
0
 

Author Comment

by:FairyBusiness
ID: 35502627
nope neither worked

not sure why its so difficult to get rid of when I had such a hard time trying to get it store it in the beginning lol
0
Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
LVL 82

Expert Comment

by:hielo
ID: 35502691
try:

<?php
session_start();//your page needs to have this at the very top

removeItem();

function removeItem() {
      if((isset($_POST['delete'])) && (isset($_POST['item']))) {
        $item = $_POST['item'];
        if( !is_array($_POST['item']) && isset($_SESSION['cart'][$item]) )
        {
            unset($_SESSION['cart'][$item]);
        }
        else
        {
            foreach($_POST['item'] as $v){
               if( isset($_SESSION['cart'][$v]) )
               {
                  unset($_SESSION['cart'][$v]);
               }
            }
        }
      }
}
?>

Open in new window

0
 
LVL 8

Accepted Solution

by:
kumaranmca earned 1000 total points
ID: 35503934
Hi,

There are two functions delete the session values.

session_destroy() -- contains clear all session variables

unset() -- to specify the session variable only.

Refer the below urls. it might be helpful for your needs.

http://www.php.net/manual/en/function.session-unset.php

http://www.php.net/manual/en/function.session-destroy.php
0
 
LVL 13

Expert Comment

by:haloexpertsexchange
ID: 35505002
If you just want to get rid of the actual value in the session, not the session itself you can try this.
$_SESSION['cart']="";

Open in new window

That sets the cart session variable to a blank string value effectively clearing it out.
0
 
LVL 111

Assisted Solution

by:Ray Paseur
Ray Paseur earned 1000 total points
ID: 35505035
One of the really great things about PHP is the online documentation.  For example, consider this statement:

empty($cart[$item]);

Want to know what the empty() function does and what it returns?  Look no further than this:
http://us3.php.net/manual/en/function.empty.php

The instruction you want is unset() and you might be able to use it this way.  Note the use of else to help with the visualization of logic.  I am not sure I would write a function that gets called this way - I think I might test for the delete signals outside of the function and only call it if the delete signals were present.  Just a thought, ~Ray
function removeItem() 
{
    if((isset($_POST['delete'])) && (isset($_POST['item']))) 
    {
        $item = $_POST['item'];
        unset($_SESSION['cart'][$item]);
    }
    else
    {
        echo "LOGIC FAILURE - ATTEMPT TO REMOVE $item NOT IN CART";
    }
}

Open in new window

0
 

Author Comment

by:FairyBusiness
ID: 35505127
Ok, I did this:

function removeItem() {
      if((isset($_POST['delete'])) && (isset($_POST['item']))) {
        $item = $_POST['item'];
        if( !is_array($_POST['item']) && isset($_SESSION['cart'][$item]) )
        {
            unset($_SESSION['cart'][$item]);
        }
        else
        {
            foreach($_POST['item'] as $v){
               if( isset($_SESSION['cart'][$v]) )
               {
                  unset($_SESSION['cart'][$v]);
				  $_SESSION['cart'][$v] = "";
               }
            }
        }
      }
}

Open in new window


Now when I hit delete it shows the shopping cart as updated (the item as deleted) but if I hit the back button it come back!  What does that mean??
0
 
LVL 13

Expert Comment

by:haloexpertsexchange
ID: 35505162
That would be old cached data that the browser is so helpfully storing for you.
0
 
LVL 13

Expert Comment

by:haloexpertsexchange
ID: 35505164
What happens when you hit the back button and then refresh the page?
0
 

Author Comment

by:FairyBusiness
ID: 35505195
It stays. Thats what worries me.  Here add these two products:

http://auroriella.com/bracelet.php?item=b3

http://auroriella.com/bracelet.php?item=b4

then remove one. Then hit the back button. Then refresh.  Tell me what you think
0
 
LVL 13

Expert Comment

by:haloexpertsexchange
ID: 35505316
Some of the problem has to do with the fact that when you press the back button, you end up resubmitting a form and then the information is resent and the session is probably being reset by that.
On the plus side when you click on the update button, the item will stay deleted. So what are you doing special with that update button?
0
 

Author Comment

by:FairyBusiness
ID: 35505372
Oh that weird.  The update button was suppose to be for adjusting the quantities:

function updateCart() {
	if((isset($_POST['update'])) && (isset($_POST['qty'])) && (isset($_POST['item']))) {
		$item = trim(mysql_clean_strings($_POST['item']));
		$qty = trim(mysql_clean_strings($_POST['qty']));
		$cart = $_SESSION['cart'];
		$_SESSION['cart'][$item] = $qty;
		var_dump($qty);
		return $qty;
	}
}

Open in new window


I didn't think I did anything special lol

I calling update before remove

updateCart();
removeItem();

I just switched them and now I am calling remove first so I think that takes care of that.

Is there anything wrong with my foreach statement?

function removeItem() {
      if((isset($_POST['delete'])) && (isset($_POST['item']))) {
        $item = $_POST['item'];
        if( !is_array($_POST['item']) && isset($_SESSION['cart'][$item]) )
        {
            unset($_SESSION['cart'][$item]);
        }
        else
        {
            foreach($_POST['item'] as $v){
               if( isset($_SESSION['cart'][$v]) )
               {
                  unset($_SESSION['cart'][$v]);
				  $_SESSION['cart'][$v] = "";
               }
            }
        }
      }
}

Open in new window


I got a warning saying it was invalid.  But I can't get the warning to come back so I'm not sure what triggered it.
0
 
LVL 82

Expert Comment

by:hielo
ID: 35505605
>>Is there anything wrong with my foreach statement?
Get rid of line 14. Line 13 already got rid of the item so you don't need it. As a matter of fact, you are "readding" the item just removed, but are specifying no quantity for it!
0
 

Author Comment

by:FairyBusiness
ID: 35505631
Darn if I hit the back button its coming back now. I tried both, and then each separately. It was working before  :(

unset($_SESSION['cart'][$v]);
 $_SESSION['cart'][$v] = "";
0
 
LVL 13

Expert Comment

by:haloexpertsexchange
ID: 35505672
try changing the isset to !empty it catches when something is set to "" as well as if it is set.
0
 

Author Comment

by:FairyBusiness
ID: 35505718
I tried this but didn't work:

function removeItem() {
      if((isset($_POST['delete'])) && (isset($_POST['item']))) {
        $item = $_POST['item'];
        if( !is_array($_POST['item']) && isset($_SESSION['cart'][$item]) )
        {
            unset($_SESSION['cart'][$item]);
        }
        else
        {
            foreach($_POST['item'] as $v){
               if(!empty($_SESSION['cart'][$v]) )
               {
                  unset($_SESSION['cart'][$v]);
				  $_SESSION['cart'][$v] = "";
               }
            }
        }
      }
}

Open in new window

0
 
LVL 82

Expert Comment

by:hielo
ID: 35505790
immediately AFTER you remove (after the else), try redirecting to show_cart:

...
  if()
  {
...
  }
  else
  {
...
  }
  header('show_cart.php');
  exit;
0
 

Author Comment

by:FairyBusiness
ID: 35505807
Wow even when I redirect and click back it still shows!

(the redirect is working though)

function removeItem() {
      if((isset($_POST['delete'])) && (isset($_POST['item']))) {
        $item = $_POST['item'];
        if( !is_array($_POST['item']) && isset($_SESSION['cart'][$item]) )
        {
            unset($_SESSION['cart'][$item]);
        }
        else
        {
            foreach($_POST['item'] as $v){
               if(!empty($_SESSION['cart'][$v])) {
                unset($_SESSION['cart'][$v]);
				$_SESSION['cart'][$v] = "";
              	ob_end_clean();
				redirect_to("index.php");
				}
            }
        }
      }
}

Open in new window

0
 

Author Comment

by:FairyBusiness
ID: 35505821
I tried this too:

function removeItem() {
      if((isset($_POST['delete'])) && (isset($_POST['item']))) {
        $item = $_POST['item'];
        if( !is_array($_POST['item']) && isset($_SESSION['cart'][$item]) )
        {
            unset($_SESSION['cart'][$item]);
        }
        else {
            foreach($_POST['item'] as $v){
               if(!empty($_SESSION['cart'][$v])) {
                unset($_SESSION['cart'][$v]);
				$_SESSION['cart'][$v] = "";
				}
            }
        }
       	ob_end_clean();
		redirect_to("show_cart.php");
    }
}

Open in new window

0
 
LVL 82

Expert Comment

by:hielo
ID: 35506280
OK, so currently if I click on:
http://auroriella.com/bracelet.php?item=b3

it redirects to:
http://auroriella.com/show_cart.php?action=add&bag=b3


Instead, in bracelet.php do:
$_SESSION['action']='add';
$_SESSION['action_item']='bag';
$_SESSION['cation_item_id']='b3';

and redirect to show_cart.php (without anything in the url):
in show_cart you retrieve the needed info from $_SESSION.
and after you have updated the cart you unset() 'action', 'action_item' and 'action_item_id' from the $_SESSION. That way when you (eventually) hit the back button, it would not be there anymore.

That means that in show_cart() you need to make sure you can "find" an expected action:
if( isset($_SESSION['action']) )
{
  switch( $_SESSION['action'] )
  {
    case 'add':
      //call function to addItem
      addItem($_SESSION['action_item'], $_SESSION['action_item_id']);
      unset($_SESSION['action']);
      unset($_SESSION['action_item']);
      unset($_SESSION['action_item_id']);
      break;

    case 'delete':
      //...
      break;
    default:
      //no valid action - redirect to index:
     header('index.php');
     exit();
  }
}
0
 
LVL 111

Expert Comment

by:Ray Paseur
ID: 35780096
Thanks for the points.  If you're interested in a technique that can help reduce the risk of duplicate submits, just post a question with that in the title and I'll show you what I like to do.  Best regards, ~Ray
0
 
LVL 8

Expert Comment

by:kumaranmca
ID: 35783051
Thank you for the points....
0

Featured Post

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Many old projects have bad code, but the budget doesn't exist to rewrite the codebase. You can update this code to be safer by introducing contemporary input validation, sanitation, and safer database queries.
Originally, this post was published on Monitis Blog, you can check it here . In business circles, we sometimes hear that today is the “age of the customer.” And so it is. Thanks to the enormous advances over the past few years in consumer techno…
Learn how to match and substitute tagged data using PHP regular expressions. Demonstrated on Windows 7, but also applies to other operating systems. Demonstrated technique applies to PHP (all versions) and Firefox, but very similar techniques will w…
The viewer will learn how to count occurrences of each item in an array.
Suggested Courses
Course of the Month19 days, 11 hours left to enroll

873 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question