user393964
user393964

Reputation:

Codeigniter object in session?

I'm starting out with CI and there's something I don't understand. I'm writing this login page and I'd like to add the users object to the session. How do I do that? The user object comes from my user model.. For a new instance I write:

$this->load->model('user_model', 'user');

but this won't work:

$this->session->set_userdata('userobject', $this->user);

Any ideas how this is done?

Upvotes: 1

Views: 5029

Answers (2)

Nanang F. Rozi
Nanang F. Rozi

Reputation: 151

What about serializing your model ;-)

$this->session->set_userdata('userobject', serialize($this->user));

and then unserialize it when fetching. But, be warn of CI session, it doesn't use the native PHP session, it used the limited size of cookies.

Upvotes: 1

Mitchell McKenna
Mitchell McKenna

Reputation: 2276

In the user Model create a function for retrieving the user data you want to add to session:

function get_user_data($id){
    //example query
    $query = $this->db->get_where('mytable', array('id' => $id));
    //might wanna check the data more than this but...
    if ($query->num_rows() > 0){
        return $query->row_array();
    }
    else{
        return false;
    }
}

In the controller:

$this->load->model('user_model', 'user');
$user_data = $this->user->get_user_data($id);
if(!empty($user_data)){
    $this->session->set_userdata($user_data);
}

Upvotes: 2

Related Questions