Brian Byrne
Brian Byrne

Reputation: 107

Add user id to session data (codeigniter)

Using CodeIgniter I'm trying to add the user id from the database to the session data.

I've looked at this question and it didn't work for me

Controller code:

function validate_credentials()
{       
    $this->load->model('users_model');
    $query = $this->users_model->validate();

    // if the users credentials validated...

    if($query) 
    {
        $user_id = $this->users_model->get_userID($this->input->post('email'));

        /* 

        I dont need to worry about insecure code because all incoming data 
        is filtered (set in config.php)

        */

        $data = array(
            'username' => $this->input->post('username'), 
            'is_logged_in' => true,
            'user_id' => $user_id
        );

        $this->session->set_userdata($data);

        redirect('site/members');
    }

    else 

    {
        // incorrect username or password
        $this->index(); 
    }
}   

Model code: (the column is called 'userID' in the users table of the db)

function get_userID($email){

    $this->db->where('email',$email);
    $query = $this->db->get('users');       

    foreach ($query->result() as $row)
    {
        $user_id = $row->userID;
    }

    return $user_id;

}

When I call the array in a view the user id does not appear.

<?php $this->session->userdata('user_id');?>

Upvotes: 0

Views: 8438

Answers (3)

M.chaudhry
M.chaudhry

Reputation: 651

Try to echo your Query it always help to understand your problem like try echo $user_id and $data sometimes due to small errors you dont get values in your queries echo will show you the result

Upvotes: 0

Kalpesh Patel
Kalpesh Patel

Reputation: 2822

If you just want to view userID try..

<?php echo $this->session->userdata('user_id');?>

Upvotes: 2

davidethell
davidethell

Reputation: 12018

The $this variable is not the same in a view as it is in a controller. If you want to refer to a session that way you have to get the $CI instance like this:

$CI = &get_instance();
$CI->session->userdata('user_id');

Upvotes: 0

Related Questions