CI框架AR数据库操作常用函数总结
本内容梳理了CodeIgniter框架中Active Record(AR)类用于数据库操作的常见函数,旨在为开发者提供参考与借鉴。
一、查询表记录相关操作
$this->db->select(); //选择查询的字段
$this->db->select_max();
$this->db->select_min();
$this->db->select_avg();
$this->db->select_sum();
$this->db->from(); //选择表名
$this->db->join();
$this->db->get(); //得到查询结果
$this->db->get_where();
$this->db->where();
$this->db->or_where();
$this->db->where_in();
$this->db->or_where_in();
$this->db->where_not_in();
$this->db->or_where_not_in();
$this->db->like();
$this->db->or_like();
$this->db->not_like();
$this->db->or_not_like();
$this->db->group_by();
$this->db->distinct();
$this->db->having();
$this->db->or_having();
$this->db->order_by();
$this->db->limit();
$this->db->count_all_results();
二、增加表记录相关操作
$this->db->insert();
三、更改表记录相关操作
$this->db->set();
$this->db->update();
四、删除表记录相关操作
$this->db->delete();
五、清空表记录相关操作
$this->db->empty_table();
$this->db->truncate();
六、查询缓存部分功能
$this->db->start_cache()
$this->db->stop_cache()
$this->db->flush_cache()
七、结果集处理方法
result() //返回对象数组
result_array() //返回二维数组
row() //返回一个对象
row_array() //返回一维数组
num_rows() //返回查询的行数
num_fields() //返回查询结果的字段数
free_result() //释放查询所占的资源内存
八、辅助查询与统计函数
$this->db->insert_id() //获取刚刚插入的id
$this->db->affected_rows() //修改或插入影响的行数
$this->db->count_all(); //统计记录的总条数 这一函数加入where条件无效
$this->db->last_query(); //最后一条执行的sql语句
//注意以下两个函数仅返回sql语句 不执行sql语句
$data = array('name' => $name, 'email' => $email, 'url' => $url);
$str = $this->db->insert_string('table_name', $data);
$data = array('name' => $name, 'email' => $email, 'url' => $url);
$where = "author_id = 1 AND status = 'active'";
$str = $this->db->update_string('table_name', $data, $where); //返回正确格式的更新字符串
注:关于CodeIgniter更详细的使用技巧,可参考本站提供的在线手册资源。
CodeIgniter 2.2.4用户指南链接: http://shouce.jb51.net/codeigniter2.2/
CodeIgniter 3.0用户指南链接: http://shouce.jb51.net/codeigniter3.0/
希望上述内容能对基于CodeIgniter框架的PHP程序设计工作提供实际帮助。