Codeigniter how to get userid after login

Hombre Filiz picture Hombre Filiz · Mar 15, 2015 · Viewed 9.1k times · Source

I have successfully created a registration and login system.
I have used useremail and password in the login form and I want to display the username and other properties related to that logged in user.

What are the simplest and best practices to get the userid after a login in codeigniter?

Answer

Irshad Ali Jan picture Irshad Ali Jan · Mar 15, 2015

Best practice would be that when you check the login details in your model after success you should create a session saving userid of that user and use that anywhere in your application for fetching respective data against that user. Take a look at following psuedo code for login user.

    public function userAuthentication($username,$pass)
{

$this->db->select('id');
$this->db->where('username',$username);
$this->db->where('password',md5($pass));
$result = $this->db->get('users')->result();

if(!empty($result)){
   $this->session->set_userdata('userlogged_in', $result[0]->id);
  return true;
}else{
  return false;
}

}

You can place this function in your model and apply it in your controller. I hope this helps.