1. 程式人生 > >PHP 依據 Mysqli 類庫打造完美分頁

PHP 依據 Mysqli 類庫打造完美分頁

本篇文章是基於的是我的上篇博文(PHP資料庫操作之基於 Mysqli 的資料庫操作類庫)而量身打造,怎麼使用 M 類庫中的 FetchAll 方法做出完美分頁。

分頁在我們每個專案中都是必不可少的,而且出現的頻率非常之多。這樣就要求我們程式設計師在專案中怎樣去以最快的速度最簡潔的程式碼去實現分頁方案。

分頁的實現大部分是依據 URL 傳入的引數(一般是page)來實現,比如:http://localhost/article.php?page=2 表示取第二頁資料

建議:您在看本篇文章之時,請確保您已學習過我的上篇博文 >>> 【點選學習

下面我們根據 M 類庫來進行分頁的講解,博文中出現的程式碼,最後附有下載地址,包括測試資料庫檔案。

1、建立配置檔案 config.inc.php

程式碼清單如下

<?php 
header('Content-Type:text/html;Charset=utf-8'); //設定header編碼
define('ROOT_PATH', dirname(__FILE__)); //設定根目錄
define('DB_HOST', 'localhost'); //資料庫伺服器地址
define('DB_USER', 'root');  //資料庫使用者名稱
define('DB_PWD', '×××');//資料庫密碼,請根據機器填寫
define('DB_NAME', '×××');  //資料庫名稱,請根據機器填寫
define('DB_PORT', '3306');  //資料庫埠,請根據機器填寫
function __autoload($className) {
    require_once ROOT_PATH . '/includes/'. ucfirst($className) .'.class.php'; //自動載入類庫檔案
}
?>

2、建立資訊測試檔案 article.php

注:因本人 CSS 能力有限,所以為了演示功能,只使用了單純的 HTML

程式碼清單及註釋如下

<?php
require 'config.inc.php'; //引入配置檔案
$m = new M(); //例項化 M 類
$total = $m->Total('jzy_article'); //資訊文章總數
$page = new Page($total, 20); //例項化分頁類
/*
注意事項:
1、例項分頁 Page 類的時候,需要傳兩個引數:記錄總數;每頁顯示的記錄數。
2、當傳入引數後,Page 類中有個setLimit()方法會自動計算出 SQL 中的 limit 值。比如:URL 引數中 page 為1的時候,limit 值為“0,20”;為2的時候,limit 值為“20,20”……
3、計算出來的 $page->limit,必須放在 FetchAll 方法中的最後一位,詳情請檢視 FetchAll 方法
*/
$data = $m->FetchAll("jzy_article", "title, source, writer, pubdate", "", "id DESC", $page->limit); //根據 M 類庫中的 FetchAll 方法獲取資料
?>
<style>
/* 分頁樣式 */
#page {text-align:right;    padding:10px;clear:both;}#page a {border:1px solid #666;padding:2px 5px;margin:0 2px;color:#3b6ea5;text-decoration:none;}#page a:hover,#page span.me {color:#fff;border:1px solid #000;background:#000;text-decoration:none;}#page span.disabled {border:1px solid #ccc;padding:2px 5px;margin:0 2px;color:#ccc;}#page span.me {padding:2px 5px;margin:0 2px;}
</style>
<table width="1000" border="1" style="border-collapse:collapse; font-size:13px;">
<tr height="30">
    <th width="483">標題</th>
    <th width="141">來源</th>
    <th width="154">作者</th>
    <th width="194">新增時間</th>
</tr>
<?php
foreach ($data as $v) { //迴圈取出資料
?>
<tr>
    <td>  <?php echo $v['title']; ?></td>
    <td align="center"><?php echo $v['source']; ?></td>
    <td align="center"><?php echo $v['writer']; ?></td>
    <td align="center"><?php echo $v['pubdate']; ?></td>
</tr>
<?php
}
?>
<tr>
    <td id="page" colspan="4"><?php echo $page->fpage(); ?></td> <!-- 調出分頁類 -->
</tr>
</table>

3、訪問測試效果

開啟瀏覽器,輸入測試的url地址,你的瀏覽器應該會出現以下效果

分頁效果

如果出現錯誤,歡迎留言,大家討論。

程式碼打包下載 >>> 【點選下載