Just want to get user_id from my database and set it to the session via Codeigniter. The problem is that when I print session I can see the following result:
(
[0] => stdClass Object
(
[user_id] => 5
)
)
instead of this one:
[user_id] => 5
Can you help me to return the value from model so that the problem will not occur.
Here is my model:
public function get_user_id() {
$this->db->select('user_id');
$this->db->from('users');
$this->db->where('email',$this->input->post('email'));
$query = $this->db->get();
if ($query->num_rows() == 1) {
return $query->result();
}
else{
return false;
}
}
Here is my controller:
$user_id = $this->model_users->get_user_id();
$data = array (
'user_id' => $user_id,
'logged_in' => 1
);
$this->session->set_userdata($data);
Try, row()
instead result()
since you just wants to retrieve one row.
public function get_user_id() {
$this->db->select('user_id');
$this->db->from('users');
$this->db->where('email',$this->input->post('email'));
$query = $this->db->get();
if ($query->num_rows() == 1) {
$row= $query->row();
return $row->user_id;
}
else{
return false;
}
}
Check this to get complete list of available functions to fetch rows from query result.
Note
Just for your information, you should read parameters (GET, POST) in controller and pass to model functions.
So, your complete code would be identical to following:
Controller
$email=$this->input->post('email');
$user_id = $this->model_users->get_user_id($email);
$data = array (
'user_id' => $user_id,
'logged_in' => 1
);
$this->session->set_userdata($data);
Model
public function get_user_id($email) {
$this->db->select('user_id');
$this->db->from('users');
$this->db->where('email',$email);
$query = $this->db->get();
if ($query->num_rows() == 1) {
$row= $query->row();
return $row->user_id;
}
else{
return false;
}
}