CodeIgniter中的增删改查操作

来源:互联网 发布:众泰知豆和吉利知豆 编辑:程序博客网 时间:2024/05/17 02:12

首先,我们创建一个模型(项目目录/models/),请注意:模型名与文件名相同且必须继承数据核心类CI_Model,同时重载父类中的构造方法。CodeIgniter的数据函数类在\system\database\DB_active_rec.php

[php] view plaincopy
  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();

[php] view plaincopy
  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>  

写在模型的构造函数里,这样加载模型的同时就连接了数据库了,非常方便。


插入数据

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

$data=你要插入的数据,以数组的方式插入(键名=字段名,键值=字段值,自增主键不用写)。


更新数据

[php] view plaincopy
  1. <span style="font-size:16px;">$this->db->where('字段名','字段值');  
  2. $this->db->update('表名',修改值的数组);</span>  

查询数据

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

删除数据
[php] view plaincopy
  1. <span style="font-size:16px;">$this->db->where('字段名','字段值');  
  2. $this->db->delete('表名');</span>  

接下然就要在控制器中调用我们的模型了
[php] view plaincopy
  1. <span style="font-size:16px;">$this->load->model('模型名')//模型名就是指你在<span style="color: rgb(255, 0, 0); ">项目目录/models/</span>底下建的Model(与文件名相同)  
  2. $this->模型名->方法名</span>  

为了不想在每个控制器的方法里面都调用一次。我是这样做的
[php] view plaincopy
  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> 
0 0
原创粉丝点击