• 技术文章 >php教程 >PHP源码

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

    2016-06-08 17:24:30原创352
    本文章是一个自己的对CI框架的学习笔记,用一个完整的搜索,查找并且实现分页的程序给大家参考参考。

    举个按关键词搜索结果分页的例子,
    1.视图HTML

    代码如下 复制代码



    请输入书名、作者、出版社中的一个或多个来查询。





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

    代码如下 复制代码

    public function index() {
    $keyword = $this->input->get ( 's' );
    $offset = $this->input->get ( 'offset' );

    if (empty ( $offset )) {
    $offset = 0;
    }

    if (! empty ( $keyword )) {
    $this->load->model ( 'book_model' );
    $this->load->library ( 'pagination' );

    $per_page = 10;
    $config ['num_links'] = 5;
    $config ['base_url'] = '/index.php/' . $this->router->class . '//m.sbmmt.com/m/' . $this->router->method . '/?s=' . $keyword;
    $config ['per_page'] = $per_page;
    $config ['total_rows'] = $this->Book_Model->find_by_name ( $keyword, NULL, NULL, true );
    $config ['page_query_string'] = false;
    $config ['query_string_segment'] = 'offset'; //重新定义记录起始位置的参数名,默认为per_page

    $this->pagination->initialize ( $config );
    $data ['books'] = $this->Book_Model->find_by_name ( $keyword, $per_page, $offset );
    $this->load->view ( 'search', $data );
    } else {
    $this->load->view ( 'search' );
    }
    }

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

    3.模型

    代码如下 复制代码
    public function find_by_name($name, $per_page=0, $offset = 0, $is_total = false) {
    if ($is_total) {//总数
    $query = $this->db->query ( "select count(id) as cnt from {$this->_book} where book_name like '%{$name}%'" );
    if ($query->num_rows () > 0) {
    $row = $query->row ();
    $ret = $row->cnt;
    }
    }else{//列表
    $query = $this->db->query ("select * from {$this->_book} where book_name like '%{$name}%' limit {$offset}, {$per_page}");
    $ret = $query->result ();
    }
    return $ret;
    }
    声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn核实处理。
    专题推荐:quot gt this query offset
    上一篇:PHP strlen与mb_strlen判断字符串是纯英文/纯汉字/汉英混合 下一篇:PHP缓冲ob_start和页面文件缓存

    相关文章推荐

    • PHP $ _POST函数 与$_GET函数详解• php 增加数据保存到mysql数据库实例教程• php经典分页函数_适合初学才• 创建文件夹 • 剖析PHP中的输出缓冲 flush之类

    全部评论我要评论

  • 取消发布评论发送
  • 1/1

    PHP中文网