CodeIgniter中的增刪改查操作
首先,我們創建一個模型(項目目錄/models/),請注意:模型名與文件名相同且必須繼承數據核心類CI_Model,同時重載父類中的構造方法。CodeIgniter的數據函數類在\system\database\DB_active_rec.php
[php]
view plaincopy
- <span style="font-size:16px;">class ModelName extends CI_Model
- {
- function __construct()
- {
- parent::__construct();
- }
- }</span>
連接數據庫:$this->load->database();
[php]
view plaincopy
- <span style="font-size:16px;">classModel_name extends CI_Model
- {
- function __construct()
- {
- parent::__construct();
- $this->load->database();
- }
- }</span>
寫在模型的構造函數裏,這樣加載模型的同時就連接了數據庫了,非常方便。
插入數據
[php]
view plaincopy
- <span style="font-size:16px;">$this->db->insert($tableName,$data);</span>
$data=你要插入的數據,以數組的方式插入(鍵名=字段名,鍵值=字段值,自增主鍵不用寫)。
更新數據
[php]
view plaincopy
- <span style="font-size:16px;">$this->db->where('字段名','字段值');
- $this->db->update('表名',修改值的數組);</span>
查詢數據
[php]
view plaincopy
- <span style="font-size:16px;">$this->db->where('字段名','字段值');
- $this->db->select('字段');
- $query= $this->db->get('表名');
- return$query->result();</span>
刪除數據
[php]
view plaincopy
- <span style="font-size:16px;">$this->db->where('字段名','字段值');
- $this->db->delete('表名');</span>
接下然就要在控製器中調用我們的模型了
[php]
view plaincopy
- <span style="font-size:16px;">$this->load->model('模型名')//模型名就是指你在<span >項目目錄/models/</span>底下建的Model(與文件名相同)
- $this->模型名->方法名</span>
為了不想在每個控製器的方法裏麵都調用一次。我是這樣做的
[php]
view plaincopy
- <span style="font-size:16px;">
- class ControllerName extends CI_Controller
- {
- function __construct()
- {
- parent::__construct();
- $this->load->model('模型名');
- }
- }</span>
最後更新:2017-04-03 12:55:27