1

I have a page which sets url parameters. I want to store them in a session so that they are always in the shopping cart but the session gets overwritten and there is always only one item in the cart.

<?php
// Start the session - session was set in book details and/or library search page
session_start();

if (isset($_GET['title']) && $_GET['title'] !== ""){
    $_SESSION['name'] = array();
    $title = $_GET['title'];
    array_push($_SESSION['name'],$title);

}

Retrieving the session details

<?php 


foreach ($_SESSION['name'] as $key => $val) {
   echo $val;
}
2
  • Doesn't this $_SESSION['name'] = array(); create an empty array every time it's executed? Commented Mar 17, 2020 at 18:33
  • I don't think so. I've tried it inside and outside of the if statement Commented Mar 17, 2020 at 18:42

3 Answers 3

2

The issue you are having is that it is re-declaring $_SESSION['name'] as a new array every time this code is run.

I suggest using something along the lines of:

<?php
    session_start();

    if(isset($_GET['title']) && $_GET['title'] !== ""){
        if(!isset($_SESSION['name']) && !is_array($_SESSION['name'])){
            $_SESSION['name'] = array();
        }

        array_push($_SESSION['name'], $_GET['title']);
    }
?>

This does your previous check of seeing if $_GET['title'] is set, but then does another check to ensure if $_SESSION['name'] exists and is an array. If it's not an array it declares it. The last thing it does is add your value to the array.

Sign up to request clarification or add additional context in comments.

5 Comments

Not working - Thanks very much. I see the logic in this - only if the session name hasn't been set an the session name is not a array will the array be set to empty however it's not working on my site. I get a 500 error
Sorry I missed a ) please try it again
Thank you. I don't know if it's my other code messing it up but it's adding the same item into the session twice now and still overwriting when I add another item.
Do you have other code that works with $_SESSION[‘name’]?
Thank you so much! I changed the session name and it's now working.
0

push all value to an array(make it associative array) using array push method after that assign that array in a session

Comments

-1

$ _SESSION is a superglobal array. Save the value in this field as follows:

 if (isset($_GET['title']) && $_GET['title'] !== ""){

$title = $_GET['title'];
$_SESSION['name'] = $title;

 }

1 Comment

That's going to end up the same way only one element, the "current" title.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.