Codeigniter 3 資料庫資訊在 application/config/Database.php,一般預設下只有辦法連到一個DB,這邊就來說明如何再額外連線資料庫的方法


預設連線

// 預設連線
$db['default']  =  array(
    'dsn'          => '',
    'hostname'     => 'localhost',
    'username'     => '',
    'password'     => '',
    'database'     => '',
    'dbdriver'     => 'mysqli',
    'dbprefix'     => '',
    'pconnect'     => FALSE,
    '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
);

// 預設使用方法
$result = $this->db->from()
    ->where()
    ->get()
    ->result_array();

新的連線

新連線的區塊,只需放在預設連線的方法即可。

// 新的連線
$db['new_client'] = array(
    'dsn'          => '',
    'hostname'     => 'localhost',
    'username'     => '',
    'password'     => '',
    'database'     => '',
    'dbdriver'     => 'mysqli',
    'dbprefix'     => '',
    'pconnect'     => FALSE,
    '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
);

// 新的連線使用方法
$new_client = $this->load->database('new_client', TRUE);
$result = $new_client->from()
    ->where()
    ->get()
    ->result_array();