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

Recommended Answers

All 3 Replies

Member Avatar for iamthwee

Set autoincrement on the id table for the book in the database.

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();

Thanks tapananand. Works fine now..

commented: Please write such things in the up vote and comment section and not as an answer. +3
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.