Steggie Steggie - 4 months ago 11
PHP Question

Store mutiple values in Session PHP

** UPDATE **
The code is working now. But Now I would like to have a

div
display the sessions saved. This div is on the same page as the items and is called
items
I tried using a refresh script. But this doesn't work.

Is this posible via jQuery or should I use AJAX (I'm not really "into" Ajax yet)...

Owke, lets see if I can explain this the best I can... I'm using Wordpress for a site I'm making now I would like to store the "liked" items a custom clicks.

So what I did was open a session in my header

<?php
session_start();
?>


Then on the page that needs to store the "like" I have the following code:

<?php
// Set session variables
$_SESSION["item"] = get_the_title();
?>


And where I would like to
echo
it I placed this code:

<?php
if(isset($_SESSION['item'])){
echo $_SESSION['item'];
};
?>


This all works like it should, BUT there are multiple items a custom could like on one page. AND I would like to store all of them in my session. But it only stores 1 session at a time.

Do I need to work with numbers of prefixes, like item-x and item-y?

I found this bit of code: link

But because I'm using Wordpress and I just want the title I cant replace $apples, $oranges and $pears with your product ids. Because for me its just

<?php the_title(); ?>


So this, for me, won't work:

<?php
// Set session variables
$_SESSION["boot"] = array();
$_SESSION["boot"][] = the_title();
?>


Every time... how to get this to work?

Answer

You are overwriting your item session every time. You need to make this an array.

$_SESSION["item"][] = get_the_title();

Now to echo them, you want to get rid of duplicates, so use array_unique()

if(isset($_SESSION['item'])){
    echo implode("<br />", array_unique($_SESSION['item']));
}

POC: https://repl.it/Cd7l

Comments