大家好,我在CI中连接多个数据库时遇到错误。当我连接到多个数据库时,有人能指出我正确的方法。
这是我的database.php文件
$active_group = 'default';
$active_record = TRUE;
$db['default']['hostname'] = 'localhost';
$db['default']['username'] = 'root';
$db['default']['password'] = 'root';
$db['default']['database'] = 'cizacl';
$db['default']['dbdriver'] = 'mysql';
$db['default']['dbprefix'] = '';
$db['default']['pconnect'] = TRUE;
$db['default']['db_debug'] = TRUE;
$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;
$active_group = 'alternate';
$active_record = TRUE;
$db['alternate']['hostname'] = 'localhost';
$db['alternate']['username'] = 'root';
$db['alternate']['password'] = 'root';
$db['alternate']['database'] = 'vkwow_auth';
$db['alternate']['dbdriver'] = 'mysql';
$db['alternate']['dbprefix'] = '';
$db['alternate']['pconnect'] = TRUE;
$db['alternate']['db_debug'] = TRUE;
$db['alternate']['cache_on'] = FALSE;
$db['alternate']['cachedir'] = '';
$db['alternate']['char_set'] = 'utf8';
$db['alternate']['dbcollat'] = 'utf8_general_ci';
$db['alternate']['swap_pre'] = '';
$db['alternate']['autoinit'] = TRUE;
$db['alternate']['stricton'] = FALSE;
然后这将检索我的模型中的所有记录功能
function getAll(){
$DB1 = $this->load->database('default',TRUE);
$DB2 = $this->load->database('alternate',TRUE);
//retrieve default DB
$query = $DB1->get('users');
if($query->num_rows() > 0){
foreach($query->result() as $row){
$data[] = $row;
}
return $data;
}
//retrieve alternate db
$query = $DB2->get('admins');
if($query->num_rows() > 0){
foreach($query->result() as $row){
$data[] = $row;
}
return $data;
}
}
这是我的输出视图代码
<p>
<?php foreach($records as $row) : ?>
<h1><?php echo $row->user_username;?></h1>
<?php endforeach; ?>
</p>
<p>
<?php foreach($records as $row) : ?>
<h1><?php echo $row->username;?></h1>
<?php endforeach; ?>
</p>
当我运行此程序时出现错误表'vkwow_auth.users'不存在
我感谢任何反馈/正确的方式来连接多个数据库。
答案 0 :(得分:1)
我不知道这实际上是你的问题 - 但为什么要从模型中的DB1返回$ data?因为它实际上从未达到DB2请求。
您需要创建一个数组,然后将结果合并到那里。
function getAll()
{
$DB1 = $this->load->database('default',TRUE);
$DB2 = $this->load->database('alternate',TRUE);
$data = new_array();
//retrieve default DB
$query = $DB1->get('users');
if($query->num_rows() > 0)
{
foreach($query->result() as $row)
{
$data['db1'][] = $row;
}
}
//retrieve alternate db
$query = $DB2->get('admins');
if($query->num_rows() > 0)
{
foreach($query->result() as $row)
{
$data['db2'][] = $row;
}
}
return $data;
}
然后只需更改视图输出以显示每个数组
编辑:&#34;当我运行这个程序时,我得到错误表'vkwow_auth.users'不存在&#34; - 这实际上听起来不像数据库连接错误 - 看起来更像是一个查询错误?