开发者社区> 问答> 正文

Codeigniter-多个数据库连接

我必须从主数据库中检索MySQL数据库信息,然后连接到该数据库,并获取一些记录。

我的意思是持有一个数据库,我想加载另一个数据库。

Codeigniter是否可能?现在,我在模型中使用以下代码行。

function connectDb($credential) {

$config['hostname'] = $credential['server'];
$config['username'] = $credential['username'];
$config['password'] = $credential['password'];
$config['database'] = $credential['database'];
$config['dbdriver'] = "mysql";
$config['dbprefix'] = "";
$config['pconnect'] = FALSE;
$config['db_debug'] = TRUE;
$config['cache_on'] = FALSE;
$config['cachedir'] = "";
$config['char_set'] = "utf8";
$config['dbcollat'] = "utf8_general_ci";

$DB2=$this->load->database($config);

$DB2->db->select('first_name,last_name');
$query = $DB2->db->get('person');
print_r($query);

} 它不起作用还有其他办法吗?

展开
收起
保持可爱mmm 2020-05-10 22:11:52 411 0
1 条回答
写回答
取消 提交回答
  • 您应该在“ application / config / database.php”中提供第二个数据库信息。

    通常,您将设置default数据库组,如下所示:

    $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; 请注意,登录信息和设置在名为的数组中提供$db['default']。

    然后,您可以在新数组中添加另一个数据库-我们将其称为“ otherdb”。

    $db['otherdb']['hostname'] = "localhost"; $db['otherdb']['username'] = "root"; $db['otherdb']['password'] = ""; $db['otherdb']['database'] = "other_database_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; 现在,要实际使用第二个数据库,必须将连接发送到可以在模型中使用的另一个变量:

    function my_model_method() { $otherdb = $this->load->database('otherdb', TRUE); // the TRUE paramater tells CI that you'd like to return the database object.

    $query = $otherdb->select('first_name, last_name')->get('person'); var_dump($query); } 那应该做。可在以下位置找到用于连接到多个数据库的文档:http : //codeigniter.com/user_guide/database/connecting.html来源:stack overflow

    2020-05-10 22:12:03
    赞同 展开评论 打赏
问答排行榜
最热
最新

相关电子书

更多
低代码开发师(初级)实战教程 立即下载
冬季实战营第三期:MySQL数据库进阶实战 立即下载
阿里巴巴DevOps 最佳实践手册 立即下载