0

I'm trying to push items into an array. Each time a user clicks a book link, the id of the book is supposed to be added to an array.(The name and id of the book are pulled from the database.) But when i push a new book id, the existing id is replaced with the new one. So there's always only one item in the array. My code

//This page is accessed when a user clicks a link
<?php
session_start();

//Here i just obtain the id and name of the book that was clicked
$id = isset($_GET['id']) ? $_GET['id'] : "";
$name = isset($_GET['name']) ? $_GET['name'] : "";


 $_SESSION['book'] = array();

// check if the book is in the array, if it is, do not add
if(in_array($id, $_SESSION['book'])){
    header('Location: notadded.php);
} 
// else, add the book to the array
else{

    array_push($_SESSION['book'], $id); 
    header('Location: added.php);
}

?>

Please how do i push new book ids into the array without replacing the existing ids. Thanks

3
Contributors
3
Replies
12
Views
3 Years
Discussion Span
Last Post by dhani09
0

The line: $_SESSION['book'] = array(); is truncating the array to size zero every time this code runs so you will have only one element each time. Instead, do something like this:

if(!isset($_SESSION['book']))
    $_SESSION['book'] = array();
1

Thanks tapananand. Works fine now..

Votes + Comments
Please write such things in the up vote and comment section and not as an answer.
This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.