ci框架里面封装数据库操作类
新手,求大神帮忙整一下谢谢啦 有人在吗进来帮帮忙吧{:soso__3669389859068460655_4:} 大婶们来帮帮小弟吧 :L 写到model里然后控制器直接调用 本帖最后由 Closer 于 2014-12-26 09:55 编辑1. 在 models 資料夾建立 test_model.php (名稱請自定義)
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Test_model extends CI_Model {
public function __construct() {
parent::__construct();
}
//搜尋單筆資料
public function get_OneData($table,$th,$td){
$query = $this->db->where($th,$td)->get($table);
if($query->num_rows() == 1){
return $query->row_array();
}
return;
}
}
2. controllers 內載入你要使用的 models,第二參數可自定義名稱
(就是不用打 test_model 那麼長一串)
$this->load->model('test_model', 'DB_m');
3. controllers 呼叫 models 內的方法 get_OneData 並傳入參數
此範例的參數分別為 資料表, 表頭, 欄位
$arrayData = $this->DB_m->get_OneData('system', 'sys_id', 1);
此時只要 system 資料表內的 sys_id 欄位有一個值為 1 的資料就會抓出來
譬如裡面有 sys_id, name, ip 三種欄位,你可以這樣直接使用:
echo $arrayData['sys_id'];
echo $arrayData['name'];
echo $arrayData['ip'];
另外關於載入 models 有三種方式:
1. 在 controllers 的方法內使用 (只有該 function 可以讀到)
2. 在 controllers 的 function __construct() {} 內使用 (只有該 controller 可以讀到)
3. 在 config 資料夾內的 autoload.php 自動載入於所有 controllers (所有 controllers 都可以讀到)
第三種方法有個缺點就是,你無法使用第三參數來縮短 models 的路徑或名稱
http://codeigniter.org.cn/user_guide/database/index.html
页:
[1]