• CI学习 分页


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

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


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

    2.控制器

    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 . '/' . $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;
    }

    摘自:http://blog.nengzuo.com/?p=1180

  • 相关阅读:
    appium---模拟点击事件
    python发送邮件(smtplib)
    postman---postman提示 Could not get any response
    postman---postman导出python脚本
    postman---postman生成测试报告
    python读写Excel方法(xlwt和xlrd)
    java求两个集合的交集和并集,比较器
    集合类型操作
    Random类和Math.random()方法
    final修饰和StringBuffer的几个案例(拼接,反转,对称操作)
  • 原文地址:https://www.cnblogs.com/jenqz/p/2816584.html
Copyright © 2020-2023  润新知