閱讀266 返回首頁    go 阿裏雲 go 技術社區[雲棲]


CodeIgniter中的增刪改查操作

首先,我們創建一個模型(項目目錄/models/),請注意:模型名與文件名相同且必須繼承數據核心類CI_Model,同時重載父類中的構造方法。CodeIgniter的數據函數類在\system\database\DB_active_rec.php

  1. <span style="font-size:16px;">class ModelName extends CI_Model  
  2. {  
  3.     function __construct()  
  4.     {  
  5.         parent::__construct();  
  6.     }  
  7. }</span>  

連接數據庫:$this->load->database();

  1. <span style="font-size:16px;">classModel_name extends CI_Model  
  2. {  
  3.     function __construct()  
  4.     {  
  5.         parent::__construct();  
  6.         $this->load->database();  
  7.     }  
  8. }</span>  

寫在模型的構造函數裏,這樣加載模型的同時就連接了數據庫了,非常方便。


插入數據

  1. <span style="font-size:16px;">$this->db->insert($tableName,$data);</span>  
$tableName = 是你要操作的表名。

$data=你要插入的數據,以數組的方式插入(鍵名=字段名,鍵值=字段值,自增主鍵不用寫)。


更新數據

  1. <span style="font-size:16px;">$this->db->where('字段名','字段值');  
  2. $this->db->update('表名',修改值的數組);</span>  

查詢數據

  1. <span style="font-size:16px;">$this->db->where('字段名','字段值');  
  2. $this->db->select('字段');  
  3. $query$this->db->get('表名');  
  4. return$query->result();</span>  

刪除數據
  1. <span style="font-size:16px;">$this->db->where('字段名','字段值');  
  2. $this->db->delete('表名');</span>  

接下然就要在控製器中調用我們的模型了
  1. <span style="font-size:16px;">$this->load->model('模型名')//模型名就是指你在<span >項目目錄/models/</span>底下建的Model(與文件名相同)  
  2. $this->模型名->方法名</span>  

為了不想在每個控製器的方法裏麵都調用一次。我是這樣做的
  1. <span style="font-size:16px;">  
  2. class ControllerName extends CI_Controller  
  3. {  
  4.     function __construct()  
  5.     {  
  6.         parent::__construct();  
  7.         $this->load->model('模型名');  
  8.     }  
  9. }</span> 

最後更新:2017-04-03 12:55:27

  上一篇:go Oracle SUBSTR函數
  下一篇:go ubuntu安裝離線JDK