【PHP框架之CI】一、常用操作整理

PHP框架CI常用整理

一、数据库参考

(一)查询

  1. 常规查询

    $query = $this->db->query(‘YOUR QUERY HERE’);

  2. 查询绑定

    $sql = “SELECT * FROM some_table WHERE id IN ? AND status = ? AND author = ?”;
    t h i s > d b > q u e r y ( this->db->query( sql, array(array(3, 6), ‘live’, ‘Rick’));

(二)查询结果

  1. 对象结果

    $query->result()

  2. 数组结果

    $query->result_array()

  3. 结果行

    $row = $query->row();

  4. 结果行数组

    $row = $query->row_array();

(三)查询辅助函数

  1. 返回查询结果数

    $query->num_rows();

  2. 该方法返回上一次执行的查询语句(是查询语句,不是结果)

    $this->db->last_query()

  3. 该方法用于获取数据表的总行数,第一个参数为表名

    echo $this->db->count_all(‘my_table’);

(四)查询构造器

4.1 查询
  1. $this->db->get()

    $query = $this->db->get(‘mytable’, 10, 20);

    Executes: SELECT * FROM mytable LIMIT 20, 10``

  2. $this->db->select()

    $this->db->select(‘title, content, date’);

    $query = $this->db->get(‘mytable’);

  3. $this->db->select_max()
  4. $this->db->select_min()
  5. $this->db->select_avg()
  6. $this->db->select_sum()
  7. $this->db->from()
  8. $this->db->join()

    $this->db->join(‘comments’, ‘comments.id = blogs.id’, ‘left’);

4.2 搜索
  1. $this->db->where()
    1. 简单的 key/value 方式:
      $this->db->where(‘name’, $name);
    2. 自定义 key/value 方式:
      $this->db->where(‘id <’, $id);
    3. 关联数组方式:
      $array = array(‘name !=’ => $name, ‘id <’ => $id, ‘date >’ => $date);

      t h i s > d b > w h e r e ( this->db->where( array);
  2. $this->db->or_where()
  3. $this->db->where_in()
  4. $this->db->or_where_in()
  5. $this->db->where_not_in()
  6. $this->db->or_where_not_in()
4.3 模糊查询
  1. $this->db->like()

    简单 key/value 方式:

    1. $this->db->like(‘title’, ‘match’, ‘before’); // Produces: WHERE title LIKE ‘%match’ ESCAPE ‘!’

    2. $this->db->like(‘title’, ‘match’, ‘after’); // Produces: WHERE title LIKE ‘match%’ ESCAPE ‘!’

    3. $this->db->like(‘title’, ‘match’, ‘both’); // Produces: WHERE title LIKE ‘%match%’ ESCAPE ‘!’

  2. $this->db->not_like()
  3. $this->db->group_by()
  4. $this->db->distinct()
  5. $this->db->having()
4.4 排序
  1. $this->db->order_by()

    $this->db->order_by(‘title’, ‘DESC’);

4.5 分页与计数
  1. $this->db->limit() 注意这里参数的顺序,第一个参数是count,第二次才是start

    $this->db->limit(10, 20);

  2. $this->db->count_all_results()
  3. $this->db->count_all()
4.6 插入数据
  1. $this->db->insert()
  2. $this->db->insert_batch()
4.7 更新数据
  1. $this->db->replace()
  2. $this->db->update()
  3. $this->db->update_batch()
  4. $this->db->delete()

(四)事务

  1. 运行事务

$this->db->trans_start();

$this->db->query(‘AN SQL QUERY…’);

$this->db->query(‘ANOTHER QUERY…’);

t h i s > d b > t r a n s c o m p l e t e ( ) ; < b r > i f ( this->db->trans_complete(); <br> if ( this->db->trans_status() === FALSE)

{

// generate an error… or use the > log_message() function to log your error

}

猜你喜欢

转载自blog.csdn.net/luomao2012/article/details/107404443