Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CodeIgniter adding session variable to an already defined "named session"

I already created as session named "verified" as shown below (in my login controller):

foreach($result as $row)
{
  $sess_array = array(
       'id' => $row->memberid, //Session field: id.
       'username' => $row->member_userunique //Session field: username.
  );
  // Create a session with a name verified, with the content from the array above.
  $this->session->set_userdata('verified', $sess_array);
}

Now, when a user open a page called book (with a controller named book) i want to add one more additional variable called "book_id" to my "verified" session.

This is what i have done

function index()
{
   //Add a new varible called book_id
   $this->session->set_userdata('book_id', $titleID);
}

When i tried to retrieve the 'book_id' using the following method:

    $session_data = $this->session->userdata('verified');
    $article_id = $session_data['book_id'];
    $user_id = $session_data['id'];

It only able to retrieve the 'id' however the 'book_id' is not defined. But if do a var_dump() on $this->session->all_userdata() i can see that the 'book_id' session variable has been successfully appended.

After reading the CI documentation about session, i realized that the code above will not work as i have not tell it to which session should i add the variable to.

Can anyone point me to the right direction?

like image 995
user2247377 Avatar asked Jan 13 '23 16:01

user2247377


1 Answers

You do as follows in your index() method:

$session_data = $this->session->userdata('verified');

$session_data['book_id'] = "something";

$this->session->set_userdata("verified", $session_data);

This way you retrieve the contents of the variable (i.e. the array that you persisted earlier), you add another key to the array (book_id), and then store it again. Now you will be able to do, as I assume you want to:

$sess = $this->session->userdata("verified");
echo $sess['book_id'];
like image 200
tomor Avatar answered Jan 21 '23 16:01

tomor