我正在研究代码点火器,需要在代码点火器中使用多个数据库。我已经检查过我们可以在配置文件中创建多个数据库连接。但是我需要根据所选状态在管理面板中加载差异选项卡。例如,当我选择状态"A"时,将使用状态"A"的数据库,如果我选择状态"B",则所有选项卡都将相应更改,则状态"B"的数据库将被加载,并且管理选项卡将相应更改。有没有办法在编码点火器中做到这一点?
您可以在application/config/database.php
中提供第二个数据库信息 然后,您应该设置默认数据库组,如下所示:
$db['default']['hostname'] = "localhost";
$db['default']['username'] = "root";
$db['default']['password'] = "";
$db['default']['database'] = "database_name";
$db['default']['dbdriver'] = "mysql";
$db['default']['dbprefix'] = "";
$db['default']['pconnect'] = TRUE;
$db['default']['db_debug'] = FALSE;
$db['default']['cache_on'] = FALSE;
$db['default']['cachedir'] = "";
$db['default']['char_set'] = "utf8";
$db['default']['dbcollat'] = "utf8_general_ci";
$db['default']['swap_pre'] = "";
$db['default']['autoinit'] = TRUE;
$db['default']['stricton'] = FALSE;
然后,可以在新数组中添加另一个数据库。 我们将辅助数据库称为otherdb
。
$db['otherdb']['hostname'] = "localhost";
$db['otherdb']['username'] = "root";
$db['otherdb']['password'] = "";
$db['otherdb']['database'] = "other_db_name";
$db['otherdb']['dbdriver'] = "mysql";
$db['otherdb']['dbprefix'] = "";
$db['otherdb']['pconnect'] = TRUE;
$db['otherdb']['db_debug'] = FALSE;
$db['otherdb']['cache_on'] = FALSE;
$db['otherdb']['cachedir'] = "";
$db['otherdb']['char_set'] = "utf8";
$db['otherdb']['dbcollat'] = "utf8_general_ci";
$db['otherdb']['swap_pre'] = "";
$db['otherdb']['autoinit'] = TRUE;
$db['otherdb']['stricton'] = FALSE;
名为$db['default']
的数组中提供的主数据库设置和名为$db['otherdb']
的数组中提供的辅助数据库的设置
然后,当您使用辅助数据库时,不要忘记像这样加载:$otherdb = $this->load->database('otherdb', TRUE);
您将在application/config/database.php
中看到默认数据库设置。如下图所示
$db['db1'] = array(
'dsn' => '',
'hostname' => 'localhost',
'username' => 'root',
'password' => '',
'database' => 'mydatabase',
'dbdriver' => 'mysqli',
'dbprefix' => '',
'pconnect' => TRUE,
'db_debug' => (ENVIRONMENT !== 'production'),
'cache_on' => FALSE,
'cachedir' => '',
'char_set' => 'utf8',
'dbcollat' => 'utf8_general_ci',
'swap_pre' => '',
'encrypt' => FALSE,
'compress' => FALSE,
'stricton' => FALSE,
'failover' => array(),
'save_queries' => TRUE
);
现在,您可以像这样在同一文件的底部添加另一个数据库设置
$db['db2'] = array(
'dsn' => '',
'hostname' => 'localhost',
'username' => 'root',
'password' => '',
'database' => 'mysecond',
'dbdriver' => 'mysqli',
'dbprefix' => '',
'pconnect' => TRUE,
'db_debug' => (ENVIRONMENT !== 'production'),
'cache_on' => FALSE,
'cachedir' => '',
'char_set' => 'utf8',
'dbcollat' => 'utf8_general_ci',
'swap_pre' => '',
'encrypt' => FALSE,
'compress' => FALSE,
'stricton' => FALSE,
'failover' => array(),
'save_queries' => TRUE
);
这就是在模型文件中使用第二个数据库的方式。
<?php
class multipleDB_model extends CI_Model {
function __construct(){
parent::__construct();
//load our the second DB and put in $db2
$this->db2 = $this->load->database('db2', TRUE);
}
public function getStudents(){
$query = $this->db2->get('student');
return $query->result();
}
}
?>