php CI架構學習筆記-分頁實現程式

來源:互聯網
上載者:User

舉個按關鍵詞搜尋結果分頁的例子,
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的方法, 其中包含了一些動態參數,不是純列表,故相對比較複雜,後面會提到。

 代碼如下 複製代碼

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;
}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.