• 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Adding Items to Session Data

#1
[eluser]surf66[/eluser]
Hello...

In my system, when a user logs in, their username is added into the session data.

I would also like to run a query in order to retrieve their user_id from the database and add this into the session data as well. It is a pretty straight forward query and all usernames in the db are unique so every time I should be pulling out just one id from the db, there should be no problems there.

Below is my login function where I am setting my session data. If anyone could help, all I want to do is grab the users id from db where it matches their username and set it in session data

Thank you in advance Smile

Code:
function login(){
  $username = $this->input->post('username');
  //get the user id and set it in the session data
  $this->db->select('user_id');
  $this->db->from('student_users');
  $this->db->where('user_username', $username);  
  $query = $this->db->get();
  return $query->row_array();

  $user_id = $query['user_id'];


  $data = array(
   'username' => $this->input->post('username'), //this works fine
   'user_id' => $user_id, //this is where i want to set the user_id in session data
   'logged_in' => TRUE
  );
  $this->session->set_userdata($data);
} //function login()

#2
[eluser]Eduard Stankovic[/eluser]
You return data right after query... it means that code after return will not work Smile

#3
[eluser]surf66[/eluser]
Ahh ok thanks, but from that query, what I cant figure out is how to get the user_id and store it in a variable, do you know how?

#4
[eluser]Eduard Stankovic[/eluser]
Code:
function login(){
  $username = $this->input->post('username');
  //get the user id and set it in the session data
  $this->db->select('user_id');
  $this->db->from('student_users');
  $this->db->where('user_username', $username);  

// this one runs query
  $query = $this->db->get();
  
// this get result of previous query, ... you need to save it in variable

$result =  $query->row_array();

// now assign value from array to variable $user_id
  $user_id = $result['user_id'];


  $data = array(
   'username' => $this->input->post('username'), //this works fine
   'user_id' => $user_id, //this is where i want to set the user_id in session data
   'logged_in' => TRUE
  );
  $this->session->set_userdata($data);


// do some logic ... return bool or redirect on succes or set flashdata on error and then redirect ... whatever you want

}

It should works .... i added some comments Smile.. hope it helps

#5
[eluser]surf66[/eluser]
Thanks for your help, I am currently away from a pc I will try this out tomorrow and report back Smile

#6
[eluser]surf66[/eluser]
Thanks for everyone's help, I now have a working solution ! Hopefully it will help others in the future too!


Digg   Delicious   Reddit   Facebook   Twitter   StumbleUpon  


  Theme © 2014 iAndrew  
Powered By MyBB, © 2002-2019 MyBB Group.