如何自动创建codeigniter会话表?当我在控制器构造函数中使用creator函数时,当会话表不存在时,我会看到codeigner错误。我的代码是:
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');
...
}
我明显的错误是:
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
我完全知道之后
parent::__construct()
我的错误发生了。
只需在phpmyadmin中转到并运行此sql查询,然后使用会话。您必须在数据库中创建ci_session表才能在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`)
);
您应该使用钩子pre_controller
,但有一个问题:CodeIgniter不允许在pre_system
和pre_controller
钩子中使用DB类,因此您不能使用活动记录($this->db->query()
)安装会话表。
我知道CodeIgniter指南上写着
预控制器-在调用任何控制器之前立即调用所有基类、路由和安全检查都已完成。
但这不是真的。。。(您可以在其他文章中了解到这一点:pre_controller钩子不加载像docs-state这样的基类?)。
无论如何,您可以手动连接到数据库。这是一个有点肮脏的解决方案,但我不知道更好的解决方案。
这是我自动安装会话表的代码。
<?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 */
下面是config/hooks.php中的代码
$hook['pre_controller'] = array(
'class' => 'SessionTableInstaller',
'function' => 'install',
'filename' => 'sessionTable.php',
'filepath' => 'hooks'
);