如何在codeigniter中连接数据库多服务器?

时间:2014-12-05 07:26:08

标签: php mysql postgresql codeigniter

我在我的本地服务器上构建项目,但文件数据库保存在另一台服务器中。我尝试在config database.php中编辑,如下所示

$active_group = 'default';
$active_record = TRUE;

$db['default']['hostname'] = 'localhost';
$db['default']['username'] = '';
$db['default']['password'] = '';
$db['default']['database'] = '';
$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;


$db['database_two']['hostname'] = 'xxx.xxx.xx.xx';
$db['database_two']['username'] = 'vtis';
$db['database_two']['password'] = '';
$db['database_two']['database'] = 'vtis';
$db['database_two']['dbdriver'] = 'postgre';
$db['database_two']['dbprefix'] = '';
$db['database_two']['pconnect'] = TRUE;
$db['database_two']['db_debug'] = TRUE;
$db['database_two']['cache_on'] = FALSE;
$db['database_two']['cachedir'] = '';
$db['database_two']['char_set'] = 'utf8';
$db['database_two']['dbcollat'] = 'utf8_general_ci';
$db['database_two']['swap_pre'] = '';
$db['database_two']['autoinit'] = TRUE;
$db['database_two']['stricton'] = FALSE;
$db['database_two']['port'] = 5432;

但我不知道之后的下一步。你能一步一步告诉我如何用codeigniter连接另一台服务器上的数据库吗?

munit_list.php

*/
class Munit_list extends CI_Model
{

    private $tbl_unit_list = 'unit_list';
    function __construct()
    {
        parent::__construct();
        $CI=&get_instance();
        $CI->database_two = $this->load->database('database_two', TRUE);
        $this->database_two =& $CI->database_two; 
    }

    function get_all_unit_list()
    {
        $this->database_two->order_by('unit_id','desc');
        $data = $this->database_two->get($this->tbl_unit_list);
        return $data->result();
    }

}

我尝试这样的模型,但它不起作用

2 个答案:

答案 0 :(得分:0)

很容易。只有这3行:

$CI=&get_instance;
$CI->database_two = $this->load->database('database_two', TRUE);
$this->database_two =& $CI->database_two; 

答案 1 :(得分:0)

在构造函数的模型中,只需添加要使用的数据库。您可以添加任意数量的数据,只要它们在数据库文件中定义即可。

类Munit_list扩展了CI_Model {

function __construct() {
    parent::__construct();
    $this->database_two= $this->load->database('database_two', TRUE); 
}

$ this-> database_two(可以是你想要的任何名字);
$ this-> load-> database('database_two',TRUE); 'database_two'是您在数据库文件中定义的名称,TRUE参数是函数返回数据库对象。

然后你就可以使用它:

function get_all_units_list(){
    $this->database_two->select("*");
    ....
    ....
}

CodeIgniter Connecting to your databases

中的更多信息