Welcome Guest, Not a member yet? Register   Sign In
Adding a user id column to CI's session table

Hi all,

I'm looking to affiliate each row in CI's session table with a particular user. The user has an id in a relating entity (different table). Have any of you found a best practice to incorporate this ID into the session table?

I'm personally thinking just adding a column, stuffing the user_id into the user's session store, then retrieving that and updating the cookie table once it's available. Not sure if I can think of a better algorithm right now.

Any ideas?


Why do you need the is on the database? What I would do is either store it in their session cookie, or use a 3rd party session library which allows session variables to be stored in the database. Both these ways means your not changing the way CI works (better for when CI upgrades)

We have used the DB Session library which stores all session info in the DB as opposed to in the cookie. You could then modify it to just add a new user_id column. Infact I think I will add this to our CMS right now cause I can see it being handy down the track Tongue

Ok all done - haven't fully tested but if I find a flaw Ill post it:

1. Install DB Sesssion Library
2. After adding the SQL required for it add the following:

ALTER TABLE `ci_sessions` ADD `user_id` INT( 11 ) NOT NULL AFTER `session_data` ;

3. Modify Session.php by adding the following to the 'sess_write_database' function (around line 302) with the following:

'last_activity'    => $this->userdata['last_activity']

if (isset($this->userdata['user_id'])) {
            $db_data['user_id'] = $this->userdata['user_id'];
        } else {
            $db_data['user_id'] = '';

4. All done! Now you can use this user_id column as you please for any future DB queries Smile

Great work, Lone! I'll look into DB Session Lib. :-)

Thanks bud,


any reason why you can't store the data in userdata? $this->session->set_userdata('id',$id); This is the kind of application specific data it's meant for.

Theme © iAndrew 2016 - Forum software by © MyBB