CodeIgniter 使用手冊版本 2.1.4


資料庫設定

CodeIgniter 提供一個設定檔讓您設定資料庫連線資料(使用者帳號(username),使用者密碼(password),資料庫名稱(database name)等…)。 The config file is located at application/config/database.php. You can also set database connection values for specific environments by placing database.php it the respective environment config folder.

資料庫設定值存放在一個多維陣列裡面:

$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;

我們使用多為陣列儲存的原因是為了讓您可以選擇性設定多組資料庫連接值。舉例來說,執行多重環境(開發 development,產品 production,測試 test) 您可以為了每一個開發環境建立獨立的資料庫設定,並且可以任意時候切換資料庫。舉例,可以設定 "test" 資料庫環境如下:

$db['test']['hostname'] = "localhost";
$db['test']['username'] = "root";
$db['test']['password'] = "";
$db['test']['database'] = "database_name";
$db['test']['dbdriver'] = "mysql";
$db['test']['dbprefix'] = "";
$db['test']['pconnect'] = TRUE;
$db['test']['db_debug'] = FALSE;
$db['test']['cache_on'] = FALSE;
$db['test']['cachedir'] = "";
$db['test']['char_set'] = "utf8";
$db['test']['dbcollat'] = "utf8_general_ci";
$db['test']['swap_pre'] = "";
$db['test']['autoinit'] = TRUE;
$db['test']['stricton'] = FALSE;

然後,可以告訴系統現在要使用 "test" 連線資料庫,並且可以隨時修改此檔案:

$active_group = "test";

注意: "test" 這名稱是可以任意修改的,可以任意設置。 系統預設值是 "default",但是可以根據專案來改變此設定。

Active Record

Active Record Class 可以根據設定檔內 $active_record 參數來進行全域設定(允許/禁止 TRUE/FALSE (boolean))。假如不想使用 active record class,請將此設定為 FALSE,以便讓系統降低初始化資料庫所需要的資源。

$active_record = TRUE;

注意: 一些 CodeIgniter 類別,像是 Sessions,在執行一些函數的時候,需要用到 Active Records。

參數設定:

注意: 並非所有的設定都是需要的,必須根據使用的資料庫 (MySQL,Postgres,etc.) 來決定。 舉例來說,使用 SQLite 資料庫的時候,就不需要設定使用者帳號跟使用者密碼,只需要設定資料庫所在的路徑位置即可。本頁範例是假設使用 MySQL 資料庫。