Skip to content
Advertisement

How can I save session values as array on button click and display on another page?

I am trying to start a session which saves product names to an array on the click of a button – these can then be retrieved and displayed on a page called ‘favourites’, which is just essentially a list of the products that the viewer is saving with the session button. I seemed to have this partially working i.e. it was showing the array on my favourites page at first, but now it is not showing any results at all…

I’m new to this and I’ve tried rewriting from scratch but I’m pulling my hair out and I am hoping someone can help by spotting an obvious mistake!

I have the following code at the very start of my product page:

   <?php
     session_start();
     if($_POST['submit'])
     {
      if(count($_SESSION['arr'])==0)
      {
       $ar=array();
       $val=$_POST['value'];
       array_push($ar,$val);
       $_SESSION['arr']=$ar;
      }
      else
      {
       $val=$_POST['value'];
       array_push($_SESSION['arr'],$val);
      }
     }
    ?>

With the following code within the same page (to create the button):

<form action="/favourites" method="post">
  <input type="hidden" name="value" value="<?php echo $pn;?>">
  <input type="submit" name="submit" value="Submit">
</form>

(Note: <?php echo $pn;?> calls the product name from my database)

Then, at the top of the favourites page I have:

<?php
 session_start();
?>

And within the favourties page I am trying to display the content of the session with:

<?php 
print_R($_SESSION['arr']);
?>

Currently my favourites page isn’t printing the array at all, it is just blank.

Advertisement

Answer

Use following to write session: session_write_close()

   <?php
     session_start();
     if($_POST['submit'])
     {
        if(count($_SESSION['arr'])==0)
        {
           $ar=array();
           $val=$_POST['value'];
           array_push($ar,$val);
           $_SESSION['arr']=$ar;
        }
        else
        {
           $val=$_POST['value'];
           array_push($_SESSION['arr'],$val);
        }
        session_write_close();
     }
   ?>

And change code for the favourites page like this:

   <?php
     session_start();
     print_R($_SESSION['arr']);
     session_write_close();
   ?>
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement