Reputation: 566
I am using sessions and trying to create an app which will store temporary data (for now) and im using this code to add "courses" to my userCourses session array:
$_SESSION['userCourses'] = array(
$_SESSION['siteCourses'][0],
);
if(isset($_GET['id'])){
$id = $_GET['id'];
array_push($_SESSION['userCourses'], $_SESSION['siteCourses'][$id]);
}
My href is written this way:
<a class="green" href="<?php echo 'coursesDisplay.php?id='.$course[2]; ?>" >Add Course</a>
where $course[2] represents the ID of the course (think of it as Auto Increment int which is individual for every course)
Now when i click the link, it does add to my array but when i go to the site without the get request of id i this part:
...url/file.php?id=1
it does not show the courses, and furthermore whenever i add another course, the previous one is overwritten despite adding it next to the prior.
Is my logic flawed (or plain stupid), am i missing something? Is this possible using sessions or do i need to use a DB for it? Im fairly new to PHP and i wanted to make a simple app using sessions before moving onto databases.
Note: I did not forget to put start_session(); on top of the files, i just wanted to keep the question clean and didn't include entire files but if someone needs me to i can put up the entire code on drive or something and they can download it.
Upvotes: 1
Views: 74
Reputation: 1125
Looks like you are reinitialising the session variable every time the script is run. Maybe check if the session variable is empty first and only initialise if it is. Something like:
if (empty($_SESSION['userCourses'] ))
{
$_SESSION['userCourses'] = array( $_SESSION['siteCourses'][0], );
}
Upvotes: 1