PHP框架CI常用整理
一、数据库参考
(一)查询
-
常规查询
$query = $this->db->query(‘YOUR QUERY HERE’);
-
查询绑定
$sql = “SELECT * FROM some_table WHERE id IN ? AND status = ? AND author = ?”;
sql, array(array(3, 6), ‘live’, ‘Rick’));
(二)查询结果
- 对象结果
$query->result()
- 数组结果
$query->result_array()
- 结果行
$row = $query->row();
- 结果行数组
$row = $query->row_array();
(三)查询辅助函数
- 返回查询结果数
$query->num_rows();
- 该方法返回上一次执行的查询语句(是查询语句,不是结果)
$this->db->last_query()
- 该方法用于获取数据表的总行数,第一个参数为表名
echo $this->db->count_all(‘my_table’);
(四)查询构造器
4.1 查询
- $this->db->get()
$query = $this->db->get(‘mytable’, 10, 20);
Executes: SELECT * FROM mytable LIMIT 20, 10`` - $this->db->select()
$this->db->select(‘title, content, date’);
$query = $this->db->get(‘mytable’); - $this->db->select_max()
- $this->db->select_min()
- $this->db->select_avg()
- $this->db->select_sum()
- $this->db->from()
- $this->db->join()
$this->db->join(‘comments’, ‘comments.id = blogs.id’, ‘left’);
4.2 搜索
- $this->db->where()
- 简单的 key/value 方式:
$this->db->where(‘name’, $name); - 自定义 key/value 方式:
$this->db->where(‘id <’, $id); - 关联数组方式:
$array = array(‘name !=’ => $name, ‘id <’ => $id, ‘date >’ => $date);
array);
- 简单的 key/value 方式:
- $this->db->or_where()
- $this->db->where_in()
- $this->db->or_where_in()
- $this->db->where_not_in()
- $this->db->or_where_not_in()
4.3 模糊查询
- $this->db->like()
简单 key/value 方式:
1. $this->db->like(‘title’, ‘match’, ‘before’); // Produces: WHEREtitle
LIKE ‘%match’ ESCAPE ‘!’
2. $this->db->like(‘title’, ‘match’, ‘after’); // Produces: WHEREtitle
LIKE ‘match%’ ESCAPE ‘!’
3. $this->db->like(‘title’, ‘match’, ‘both’); // Produces: WHEREtitle
LIKE ‘%match%’ ESCAPE ‘!’ - $this->db->not_like()
- $this->db->group_by()
- $this->db->distinct()
- $this->db->having()
4.4 排序
- $this->db->order_by()
$this->db->order_by(‘title’, ‘DESC’);
4.5 分页与计数
- $this->db->limit()
注意这里参数的顺序,第一个参数是count,第二次才是start
$this->db->limit(10, 20);
- $this->db->count_all_results()
- $this->db->count_all()
4.6 插入数据
- $this->db->insert()
- $this->db->insert_batch()
4.7 更新数据
- $this->db->replace()
- $this->db->update()
- $this->db->update_batch()
- $this->db->delete()
(四)事务
- 运行事务
$this->db->trans_start();
$this->db->query(‘AN SQL QUERY…’);
$this->db->query(‘ANOTHER QUERY…’);
this->db->trans_status() === FALSE)
{
// generate an error… or use the > log_message() function to log your error
}