有的時候我們會有操作不同資料庫的需求,CI 是可以支援這樣做的, 所以我們可以很輕鬆的達到這個功能!
環境:
CentOS 7 x64 PHP 7.0.12 + PHP-FPM Code Igniter 3.0.6 MySQL 5.6
首先設定 CI 的 Database 設定檔 application\config\database.php
#預設的資料庫
$db['default'] = array(
'dsn' => '',
'hostname' => 'localhost',
'username' => 'DB1',
'password' => '12345678',
'database' => 'DB1',
'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
);
#第二組資料庫
$db['db2'] = array(
'dsn' => '',
'hostname' => 'localhost',
'username' => 'DB2',
'password' => '12345678',
'database' => 'DB2',
'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
);
由於是操作不同資料庫,為了避免搞混,所以我習慣獨立開一個 Model 檔案,我們可以在新的 Model 的 __construct 設定
function __construct()
{
$CI = &get_instance();
$this->db_db2 = $CI->load->database('db2', TRUE);
}
然後就可以寫個簡單的 Function 來讀取 db2 的資料
public function select_db2()
{
$this->db2->from('db2.table');
return $this->db2->get()->result();
}
這樣就完成囉,當然你也可以丟到 Library 再來呼叫,做法是一樣的。
參考資料:http://tutsnare.com/connecting-multiple-database-in-codeigniter
發佈留言