這次帶給大家php框架CodeIgniter資料庫設定步驟詳解,php框架CodeIgniter資料庫配置的注意事項有哪些,下面就是實戰案例,一起來看一下。
CodeIgniter簡稱CI是最受歡迎的一個php MVC框架之一,本人講從實際專案使用中寫系列實戰經驗,有別與其他的理論講解文章,會附上實戰流程和程式碼。
本篇為配置多個資料庫,使用場景為集群,分佈式,資料庫讀寫分離,多台主從互備只有一台為讀寫資料庫,其他為唯讀資料庫。
工具/環境:
php開發環境
CodeIgniter
##方法/步驟:
在config/database.php 裡面配置多一個資料庫來源,default為預設的可以是localhost也可以是IP,writedb為可讀寫的資料庫,由於寫的為主從互備的需要用IP遠端調用,本人配置為:$active_group = 'default'; $active_record = TRUE; $db['default']['hostname'] = 'localhost'; $db['default']['username'] = 'default_username'; $db['default']['password'] = 'default_password'; $db['default']['database'] = 'default_dbname'; $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; $db['writedb']['hostname'] = '202.187.194.160'; $db['writedb']['username'] = 'writedb_name'; $db['writedb']['password'] = 'writedb_password'; $db['writedb']['database'] = 'writedb_db'; $db['writedb']['dbdriver'] = 'mysql'; $db['writedb']['dbprefix'] = ''; $db['writedb']['pconnect'] = TRUE; $db['writedb']['db_debug'] = TRUE; $db['writedb']['cache_on'] = FALSE; $db['writedb']['cachedir'] = ''; $db['writedb']['char_set'] = 'utf8'; $db['writedb']['char_names'] = 'utf8'; $db['writedb']['dbcollat'] = 'utf8_general_ci'; $db['writedb']['swap_pre'] = ''; $db['writedb']['autoinit'] = TRUE; $db['writedb']['stricton'] = FALSE;
<?php class Feedbackmodel extends CI_Model { function construct() { parent::construct (); $this->db = $this->load->database ('default',true); $this->writedb = $this->load->database ('writedb',true); } public function add($data) { $this->writedb->insert('feedback',$data); if($this->writedb->affected_rows() == 1){ return true; } return false ; } } ?>
控制器的呼叫跟普通的一樣,只要引入Model就可以了,本人實例:
<?php class Feedback extends CI_Controller { function construct(){ parent::construct(); } function index(){ $this->load->model('feedbackmodel'); $this->load->helper('url'); $data['name'] = "feedback"; $this->load->view('feedbackview',$data); } } ?>
以上是php框架CodeIgniter資料庫設定步驟詳解的詳細內容。更多資訊請關注PHP中文網其他相關文章!