Codeigniter how to get userid after login Codeigniter how to get userid after login codeigniter codeigniter

Codeigniter how to get userid after login


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.


As good coder create session at login time and use session at website wide.

public function login($username, $password) {    $user = $this->db        ->select("username, name, phone")        ->where(             [                'username' => $username,                'password' => md5($password)             ]         )        ->get("table_name")        ->row();   if ($user) {         $logindata = [             'userid' => $user->username,             'name'   => $user->name,             'phone'  => $user->phone         ];         $this->session              ->set_userdata($logindata);         return true;   }   else {         return false;   }} 

Then after you can use anywhere in website

echo $this->session->userid;

I hope it will help you in general way.


You may create a session and set user id after successful login.