首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 綜合知識

CodeIgniter 分頁類 Pagination 完整實戰範例:Controller、Model、View 三層協作

     編輯:PHP 綜合知識

完整 MVC 實作範例

Controller:application/controllers/Page.php

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'] = '
    '; $config['full_tag_close'] = '
'; $config['num_tag_open'] = '
  • '; $config['num_tag_close'] = '
  • '; $config['cur_tag_open'] = '
  • '; $config['cur_tag_close'] = '
  • '; $config['next_tag_open'] = '
  • '; $config['next_tag_close'] = '
  • '; $config['prev_tag_open'] = '
  • '; $config['prev_tag_close'] = '
  • '; $config['first_tag_open'] = '
  • '; $config['first_tag_close'] = '
  • '; $config['last_tag_open'] = '
  • '; $config['last_tag_close'] = '
  • '; $this->load->library('pagination'); $this->pagination->initialize($config); // 5. 準備視圖資料 $viewData = [ 'list' => $result['list'], 'total' => $result['total'], 'current_page' => $current_page, 'per_page' => $this->per_page, 'pagination' => $this->pagination->create_links(), ]; $this->load->view('page/index', $viewData); } }

    Model:application/models/Home_model.php

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

    View:application/views/page/index.php

    <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連結顯示頁碼而非 offsetTRUE
    num_links當前頁前後顯示頁碼數3

    常見問題與解決

    1. 分頁連結點擊無反應:檢查 base_url 是否正確、page_query_string 與實際 URL 格式一致。
    2. 總筆數不正確:count_all_results() 會重置 Query Builder 狀態,確保查詢條件一致。
    3. 頁碼顯示異常:use_page_numbers=TRUE 時,per_page 參數傳遞的是頁碼,Controller 需自行計算 offset。
    4. 樣式錯亂:確認 full_tag_open/close 等標籤正確巢狀、引用正確 CSS 框架版本。

    進階:AJAX 無刷新分頁

    $('.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 Cache Library)。
    • 避免在迴圈中查詢關聯資料,使用 JOIN 或批次預載。

    此範例展示了 CI 分頁類別在真實專案中的完整應用流程,涵蓋 Controller 參數處理、Model 查詢分離、View 樣式整合,可直接套用至專案中。

    1. 上一篇文章:
    2. 下一篇文章:
    Copyright © 程式碼之家 All Rights Reserved