Codeigniter - storing database results in session
Hey there, i want to store some session info from a database query, upon log in, but for some reason it isnt letting me set the session userdata!?!
Can anyone shed any light as to why?
Controller:
function validate_login(){
$this->load->library('form_validation');
$this->form_validation->set_rules('email_address', "Email address","required|valid_email");
$this->form_validation->set_rules('password', "Password", "trim|required|min_length[6]|max_length[32]");
if($this->form_validation->run() == FALSE){
$this->login();
} else {
$email_address = $this->input->post('email_address');
$password = md5($this->input->post('password'));
$prev_page = $this->input->post('referrer');
$found_user = $this->account_model->validate_user($email_address, $password); // calls to function of the same name in the model, returns array.
if($found_user){
$session_data = array(
'user_id' => $found_user->user_id,
'is_logged_in' => TRUE
);
// Debug code
if($this->session->set_userdata($session_data)){
echo "success session";
} else {
echo "failure session";
}
} else {
//Debug code
echo 'no user found';
开发者_Python百科}
}
}
Model:
function validate_user($email_address, $password){
$this->db->where('email_address', $email_address);
$this->db->where('password', $password);
$query = $this->db->get('user');
if($query->num_rows() == 1){
foreach($query->result() as $row){
$data = $row;
}
return $data;
} else {
return FALSE;
}
}
I'm posting this as another answer just so I can paste this code snippet. I think everything is working as it should be. The set_userdata function returns void, so you don't need to encapsulate it in an if statement.
Instead of the following code:
if($this->session->set_userdata($session_data)){
echo "success session";
} else {
echo "failure session";
}
It should just be:
this->session->set_userdata($session_data);
You can use this function to add new data or changing existing data in the session; it doesn't matter if there's already data in it.
Another answer:
Are you loading the session library? Being a commonly used library I would recommend loading it in the autoload config file, like so:
$autoload['libraries'] = array('session', 'other libraries etc');
Solved!!
Well it seems to be working now, i think the problem might have been trying to set_userdata that was already set!
although i don't know why it would return FALSE if i was updating or adding to data that was there. I made sure all session data was destroyed and cut out the conditionals and now seems to have a persistant session.
精彩评论