首页 > 解决方案 > 不同实例中的多个数据库连接以连接 codeigniter 应用程序

问题描述

我试图在单个 codeigniter 应用程序中连接多个数据库(mysql)?但是数据库在不同的服务器上。

代码点火器 3.x

遇到 PHP 错误 严重性:警告

消息:mysqli::real_connect(): (HY000/2002): 连接超时

文件名:mysqli/mysqli_driver.php

行号:203

回溯:

文件:/var/www/html/rmp/mautic_sync/mautic_ci/application/controllers/Cron.php 行:19 功能:数据库

文件:/var/www/html/rmp/mautic_sync/mautic_ci/index.php 行:315 功能:require_once

标签: phpcodeigniter

解决方案


文档:https ://www.codeigniter.com/user_guide/database/connecting.html

在 application/config/database.php 中添加新元素 $db 数组

$db['old'] = array( 'dsn' => '', 'hostname' => 'localhost', 'username' => 'root', 'password' => 'xxxxx', 'database' => 'you_database_name', 'dbdriver' => 'mysqli', 'dbprefix' => '', 'pconnect' => FALSE, 'db_debug' => (ENVIRONMENT !== 'production'), 'cache_on' => FALSE, 'cachedir' => '', 'char_set' => 'utf8mb4', 'dbcollat' => 'utf8_general_ci', 'swap_pre' => '', 'encrypt' => FALSE, 'compress' => FALSE, 'stricton' => FALSE, 'failover' => array(), 'save_queries' => TRUE );

利用:

class YourController extends CI_Controller {

 private $old_db = "";
function __construct() {
    parent::__construct();
    $this->old_db = $this->load->database('old', true);
}
public function index(){
    $query = $this->old_db->get('table_name');
    print_r($query->result());
}

}

推荐阅读