一個簡潔、可重複使用的 PHP 分頁類別,支援總頁數計算、當前頁碼、上一頁/下一頁、首頁/末頁、頁碼清單與下拉跳轉選單。
class Multipage { var $total; // 總筆數 var $perpage; // 每頁筆數 var $pages; // 總頁數 var $maxpage; // 最大顯示頁碼數 var $offset = 9; // 當前頁前後偏移量 var $curr_page; // 當前頁碼 // 初始化 function init($total, $perpage, $maxpage) { $this->total = $total; $this->perpage = $perpage; $this->maxpage = $maxpage; $this->offset = 9; } // 取得頁碼清單陣列 function getPageList() { $result_pages = array(); $this->pages = ceil($this->total / $this->perpage); if ($this->pages > $this->maxpage) { $from = $this->curr_page - $this->offset; if ($from < 1) $from = 1; $to = $from + $this->maxpage - 1; if ($to > $this->pages) { $to = $this->pages; if (($to - $from) < $this->maxpage) $from = max(1, $to - $this->maxpage + 1); } } else { $from = 1; $to = $this->pages; } for ($i = $from; $i <= $to; $i++) { $result_pages[] = $i; } return $result_pages; } // 取得首頁頁碼 function getFirst() { return ($this->curr_page > 1 && $this->pages > 1) ? 1 : ''; } // 取得末頁頁碼 function getLast() { return ($this->pages > 1 && $this->curr_page < $this->pages) ? $this->pages : ''; } // 取得上一頁頁碼 function getPrev() { $prev = $this->curr_page - 1; return ($prev > 0) ? $prev : ''; } // 取得下一頁頁碼 function getNext() { $next = $this->curr_page + 1; return ($next <= $this->pages) ? $next : ''; } // 取得總頁數 function getTotal() { return ($this->pages > 0) ? $this->pages : 1; } }
<?php require 'Multipage.class.php'; // 假設從資料庫查得總筆數 $total_records = 125; $per_page = 10; $max_display_pages = 10; $current_page = isset($_GET['page']) ? max(1, intval($_GET['page'])) : 1; $page = new Multipage(); $page->total = $total_records; $page->perpage = $per_page; $page->maxpage = $max_display_pages; $page->curr_page = $current_page; // 取得分頁導航資料 $page_list = $page->getPageList(); $first = $page->getFirst(); $prev = $page->getPrev(); $next = $page->getNext(); $last = $page->getLast(); $total_pages = $page->getTotal(); // 輸出分頁 HTML echo '<div class="pagination">'; if ($first) echo '<a href="?page=1">首頁</a> '; if ($prev) echo '<a href="?page=' . $prev . '">上一頁</a> '; foreach ($page_list as $p) { if ($p == $current_page) { echo '<span class="current">' . $p . '</span> '; } else { echo '<a href="?page=' . $p . '">' . $p . '</a> '; } } if ($next) echo '<a href="?page=' . $next . '">下一頁</a> '; if ($last) echo '<a href="?page=' . $last . '">末頁</a> '; echo '</div>'; // 資料庫查詢時使用 LIMIT $offset = ($current_page - 1) * $per_page; $sql = "SELECT * FROM articles LIMIT $offset, $per_page"; ?>
getLimit() 方法直接回傳 LIMIT offset, count 字串