class Page extends CI_Controller {
public $per_page = 15;
public $first_link = '首頁';
public $prev_link = '上一頁';
public $next_link = '下一頁';
public $last_link = '尾頁';
public function index() {
$this->load->model('home_model');
// 1. 取得當前頁碼(query string 方式)
$current_page = (int) $this->input->get('per_page', true);
if ($current_page < 1) $current_page = 1;
// 2. 計算 offset
$offset = ($current_page - 1) * $this->per_page;
// 3. 查詢資料
$result = $this->home_model->getList($offset, $this->per_page, 'id DESC');
// 4. 設定分頁配置
$config['base_url'] = site_url('page/index');
$config['total_rows'] = $result['total'];
$config['per_page'] = $this->per_page;
$config['page_query_string'] = TRUE;
$config['query_string_segment'] = 'per_page';
$config['num_links'] = 3;
$config['use_page_numbers'] = TRUE; // 顯示頁碼而非 offset
$config['first_link'] = $this->first_link;
$config['prev_link'] = $this->prev_link;
$config['next_link'] = $this->next_link;
$config['last_link'] = $this->last_link;
// Bootstrap 4 樣式
$config['full_tag_open'] = 'class Home_model extends CI_Model {
public function getList($offset, $limit, $order = 'id DESC') {
// 使用 Query Builder 防止 SQL 注入
$query = $this->db
->select('Name_cn, Mall_type, create_time')
->from('smzdm_mall')
->where('Is_deleted', 0)
->order_by($order)
->limit($limit, $offset)
->get();
$list = $query->result();
// 取得總筆數(用於分頁計算)
$total = $this->db
->from('smzdm_mall')
->where('Is_deleted', 0)
->count_all_results();
return [
'list' => $list,
'total' => $total,
];
}
}
<div class="container">
<h2>商場列表 (共 <?php echo $total; ?> 筆)</h2>
<table class="table table-striped">
<thead>
<tr>
<th>名稱</th>
<th>類型</th>
<th>建立時間</th>
</tr>
</thead>
<tbody>
<?php foreach ($list as $item): ?>
<tr>
<td><?php echo $item->Name_cn; ?></td>
<td><?php echo $item->Mall_type; ?></td>
<td><?php echo $item->create_time; ?></td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
<!-- 分頁導航 -->
<nav aria-label="Page navigation">
<?php echo $pagination; ?>
</nav>
</div>
| 參數 | 說明 | 本範例值 |
|---|---|---|
| base_url | 分頁連結基礎網址 | site_url('page/index') |
| total_rows | 資料總筆數 | $result['total'] |
| per_page | 每頁顯示筆數 | 15 |
| page_query_string | 使用 Query String 模式 | TRUE |
| query_string_segment | 頁碼參數名 | per_page (CI 預設) |
| use_page_numbers | 連結顯示頁碼而非 offset | TRUE |
| num_links | 當前頁前後顯示頁碼數 | 3 |
base_url 是否正確、page_query_string 與實際 URL 格式一致。count_all_results() 會重置 Query Builder 狀態,確保查詢條件一致。use_page_numbers=TRUE 時,per_page 參數傳遞的是頁碼,Controller 需自行計算 offset。full_tag_open/close 等標籤正確巢狀、引用正確 CSS 框架版本。$('.pagination a').click(function(e) {
e.preventDefault();
var url = $(this).attr('href');
$('#content-area').load(url + ' #content-area > *', function() {
// 重新綁定點擊事件(因內容已替換)
bindPaginationEvents();
});
});
SQL_CALC_FOUND_ROWS + FOUND_ROWS() 減少兩次查詢(需原生 SQL)。此範例展示了 CI 分頁類別在真實專案中的完整應用流程,涵蓋 Controller 參數處理、Model 查詢分離、View 樣式整合,可直接套用至專案中。