Codeigniter how to get userid after login
Solution 1
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.
Solution 2
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.
Related videos on Youtube
Hombre Filiz
Updated on May 25, 2022Comments
-
Hombre Filiz almost 2 years
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?
-
Phantômaxx about 9 yearsGixed some grammar and formatting
-
-
Irshad Ali Jan about 9 yearsYou are welcome, i am glad that i was able to help :) .
-
Hombre Filiz about 9 yearsThanks Ian, it was really helpful :)