[英]Create codeigniter session table automatically
如何自動創建codeigniter會話表? 當我在控制器構造函數中使用創建者函數並且會話表不存在時,我看到codeigniter錯誤。 我的代碼是:
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-在調用任何控制器之前立即調用。 所有基類,路由和安全性檢查均已完成 。
但這不是正確的...(您可以在其他文章中了解它: 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'
);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.