Step 8 (optional) – Using sessions with database in CodeIgniter

Created at: January 23, 2015; Last update: April 18, 2017

(created at: January 23, 2014; last update: April 1, 2015)
By default, session data is saved as files on the server. Here is a video tutorial of mine regarding how to use the file driver to store session data:

In this tutorial though we will learn about storing session data in the database. To do this we first need to go to the config.php file and look for the line:

We should change this line to:

Also, after this line we should write another one that will tell the CodeIgniter framework what table it should use for storing the session data (make sure it doesn’t already exist):

To create a table we should first have a database. So let’s create it. I will name mine “ciapp” and set the collation to “utf8_general_ci”. Now let’s create the table:

For MySql we can simply paste this sql command:

Now let’s set up the database.php that we have inside application/config/development directory (if you don’t have it there, you can simply move the one that is inside the config directory):

Now you go to the autoload.php, and add “session” to the drivers element:

If on visiting http://localhost you can’t see an error and by looking to the database you see at least one record (your visit), then you are ready to go. But do you need sessions across entire website? If you don’t, then it is a better idea not to “autoload” it.

4 thoughts on “Step 8 (optional) – Using sessions with database in CodeIgniter

  1. Dan

    Mercy mi-a fost de ajutor pt 3.0,
    Vezi ca ai omis sa treci ‘id’ in loc de ‘session_id’ pt primary key la create table in sql command.

    Reply
    1. avenirer Post author

      Multumesc pentru atentionare. Tutorialul a fost realizat inca inainte sa apara versiunea 3.0. Era inca in stadiul “dev” si s-ar putea ca acum sa fie unele scapari, chiar si la celelalte tutoriale. Daca mai reperezi astfel de erori, te rog sa imi spui. Multumesc.

      Reply
  2. Jacky

    Just a note to the SQL Queries above. THe MYSQL SQL standards does not need single quotes for table name and field names. Hence the below can be used instead. 🙂
    ==========================================
    CREATE TABLE IF NOT EXISTS ci_sessions (
    id varchar(40) NOT NULL,
    ip_address varchar(45) NOT NULL,
    timestamp int(10) unsigned DEFAULT 0 NOT NULL,
    data blob NOT NULL,
    PRIMARY KEY (id),
    KEY ci_sessions_timestamp (timestamp)
    );
    =========================================

    Reply
  3. Alex

    Hi,

    Your tutorials have been really helpful and i appreciate the good work. Could you write a tutorial on how to build a reusable template using codeigniter? I have been trying without much success.

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *

No spam? * Time limit is exhausted. Please reload CAPTCHA.