0

How can I create codeigniter session table automatically? When I use creator function in my controller constructor and when the session table not exist I see codeigniter error. My code is:

function admin() { 
parent::__construct();
ob_start();
if(!$this->db->table_exists('session'))//for `first time` run.
    $this->utilmodel->create_session_table(); //this function create session table with CI structure
ob_end_clean();
$this->load->library('session'); 
... 
}

My obviously error is:

Error Number: 1146    
Table 'dbs.session' doesn't exist

INSERT INTO `session` (`session_id`, `ip_address`, `user_agent`,
`last_activity`, `user_data`) VALUES
('0a78608576684ebc2c0050b8f4810f', '127.0.0.1', 'Mozilla/5.0
(Windows NT 6.1; rv:32.0) Gecko/20100101 Firefox/32.0
AlexaToolbar/alxf-2.21', 1001550875, '')

Filename: C:\wamp\www\folder\system\database\DB_driver.php

Line Number: 330

I know exactly after

parent::__construct()

my error happens.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Max
  • 1
  • 1
  • 5
  • Need more insight into your code. I am also not sure why you are trying to create the table on the fly. You are best to work with a database migration script instead of creating tables on the fly. – Thomas Hambach Sep 24 '14 at 09:43
  • yes, you need to use hooks. to be more specific `pre_system` will work. – Karan Thakkar Sep 24 '14 at 10:14
  • i should create on the fly table because of my system features. it have a configuration panel that config base system settings and etc. – Max Sep 24 '14 at 10:26
  • Yes you right, i do not think about hooks before. if my problem solved i will say here. anyway thanks so much. – Max Sep 24 '14 at 10:28

2 Answers2

0

just go to in your phpmyadmin and run this sql query then use session. you have to create ci_session table in your database to use session in codeigniter

CREATE TABLE IF NOT EXISTS  `ci_sessions` (
    session_id varchar(40) DEFAULT '0' NOT NULL,
    ip_address varchar(45) DEFAULT '0' NOT NULL,
    user_agent varchar(120) NOT NULL,
    last_activity int(10) unsigned DEFAULT 0 NOT NULL,
    user_data text NOT NULL,
    PRIMARY KEY (session_id),
    KEY `last_activity_idx` (`last_activity`)
);
Lokesh Jain
  • 579
  • 6
  • 19
  • i see but i have a creator function that do this but before running of this function codeigniter generate this error, i dont want create this table manually by phpmyadmin. – Max Sep 24 '14 at 09:45
  • if you are using session_start() then don't use it before creating session table because you can't use it without session table in CI. – Lokesh Jain Sep 24 '14 at 09:55
  • maybe session_start() function used in codeigniter constructor, if yes so where i can change codeigniter constructor? – Max Sep 24 '14 at 10:04
0

You should use hook pre_controller BUT there is one problem: CodeIgniter does not allow to use DB class in pre_system and pre_controller hooks, so you can not install session table using active record ( $this->db->query() ).

I know that CodeIgniter guide says

pre_controller - Called immediately prior to any of your controllers being called. All base classes, routing, and security checks have been done.

but this is NOT true... (you can read about it on other posts: pre_controller hook does not load base classes like docs state?).

Anyway, you can connect to your database manually. This is a little dirty solution, but I don't know better one.

Here is my code to install session table automatically.

<?php

class SessionTableInstaller
{
    public function install() 
    {
        if( $db_config = $this->getDBConfig() ) {

            $db_handle = mysql_connect($db_config['hostname'], $db_config['username'], $db_config['password']);

            if ($db_handle === FALSE) {
                throw new Exception('Cannot connect with MySql server');
            }

            if (mysql_select_db($db_config['database'], $db_handle) === FALSE) {
                throw new Exception('Cannot select database');
            }

            $query = "CREATE TABLE IF NOT EXISTS  `ci_sessions` (
                session_id varchar(40) DEFAULT '0' NOT NULL,
                ip_address varchar(45) DEFAULT '0' NOT NULL,
                user_agent varchar(120) NOT NULL,
                last_activity int(10) unsigned DEFAULT 0 NOT NULL,
                user_data text NOT NULL,
                PRIMARY KEY (session_id) ,
                KEY `last_activity_idx` (`last_activity`)
            ) ENGINE=InnoDB default CHARSET=utf8 ;";

            mysql_query($query);
            mysql_close($db_handle);
        }
    }

    private function getDBConfig()
    {
        require __DIR__ . '/../config/database.php';

        if(!isset($db) || !isset($active_group)) {
            return false;
        }

        $db_config = $db[ $active_group ];
        return $db_config;
    }
}

/* End of file sessionTable.php */
/* Location: ./application/hooks/sessionTable.php */

And here is code in config/hooks.php

$hook['pre_controller'] = array(
    'class'    => 'SessionTableInstaller',
    'function' => 'install',
    'filename' => 'sessionTable.php',
    'filepath' => 'hooks'
);
Community
  • 1
  • 1
Wiktor
  • 43
  • 7