php CI框架学习笔记-分页实现程序

本文章是一个自己的对CI框架的学习笔记,用一个完整的搜索,查找并且实现分页的程序给大家参考参考.

举个按关键词搜索结果分页的例子.

视图HTML,代码如下:

  1. <div >
  2. <form action="/index.php/search/index/" method="get">
  3. <p>请输入书名、作者、出版社中的一个或多个来查询。</p>
  4. <p><input type="text" name="s" value="" size="64" /> <input type="submit" value="搜索" /></p>
  5. </form>
  6. </div>

即表单提交到名叫search的controller和名叫index的方法,其中包含了一些动态参数,不是纯列表,故相对比较复杂,后面会提到,代码如下:

  1. public function index() {
  2. $keyword = $this->input->get ( 's' );
  3. $offset = $this->input->get ( 'offset' );
  4. if (emptyempty ( $offset )) {
  5. $offset = 0;
  6. }
  7. if (! emptyempty ( $keyword )) {
  8. $this->load->model ( 'book_model' );
  9. $this->load->library ( 'pagination' );
  10. $per_page = 10;
  11. $config ['num_links'] = 5;
  12. $config ['base_url'] = '/index.php/' . $this->router->class . '/' . $this->router->method . '/?s=' . $keyword;
  13. $config ['per_page'] = $per_page;
  14. $config ['total_rows'] = $this->Book_Model->find_by_name ( $keyword, NULL, NULL, true );
  15. $config ['page_query_string'] = false;
  16. $config ['query_string_segment'] = 'offset'; //重新定义记录起始位置的参数名,默认为per_page
  17. $this->pagination->initialize ( $config );
  18. $data ['books'] = $this->Book_Model->find_by_name ( $keyword, $per_page, $offset );
  19. $this->load->view ( 'search', $data );
  20. } else {
  21. $this->load->view ( 'search' );
  22. }
  23. }

因为config.php中默认的enable_query_strings是false,起始位置始终在最后,这样出来的结果类似/index.php/search/index/?s=中国/10,页码取不到,需要将此配置改为false;

模型,代码如下:

  1. public function find_by_name($name, $per_page=0, $offset = 0, $is_total = false) {
  2. if ($is_total) {//总数
  3. $query = $this->db->query ( "select count(id) as cnt from {$this->_book} where book_name like '%{$name}%'" );
  4. if ($query->num_rows () > 0) {
  5. $row = $query->row ();
  6. $ret = $row->cnt;
  7. }
  8. }else{//列表
  9. $query = $this->db->query ("select * from {$this->_book} where book_name like '%{$name}%' limit {$offset}, {$per_page}");
  10. $ret = $query->result ();
  11. }
  12. return $ret;
  13. }