簡單分頁類分享 現在公布一個簡單分類制作。只要理解了這個類的原理和步驟,其他復雜類也就能夠觸類旁通了。不廢話,直接上源碼,可以直接用在你的項目中。
數據庫操作類代碼:mysqli.func.php
- <?php
- // 數據庫連接常量
- define('DB_HOST', 'localhost');
- define('DB_USER', 'root');
- define('DB_PWD', '');
- define('DB_NAME', 'guest');
-
- // 連接數據庫
- function conn()
- {
- $conn = mysqli_connect(DB_HOST, DB_USER, DB_PWD, DB_NAME);
- mysqli_query($conn, "set names utf8");
- return $conn;
- }
-
- //獲得結果集
- function doresult($sql){
- $result=mysqli_query(conn(), $sql);
- return $result;
- }
-
- //結果集轉為對象集合
- function dolists($result){
- return mysqli_fetch_array($result, MYSQL_ASSOC);
- }
-
- function totalnums($sql) {
- $result=mysqli_query(conn(), $sql);
- return $result->num_rows;
- }
-
- // 關閉數據庫
- function closedb()
- {
- if (! mysqli_close()) {
- exit('關閉異常');
- }
- }
-
- ?>
分頁實現代碼:- <?php
- include 'mysqli.func.php';
-
- // 總記錄數
- $sql = "SELECT dg_id FROM tb_user ";
- $totalnums = totalnums($sql);
-
- // 每頁顯示條數
- $fnum = 8;
-
- // 翻頁數
- $pagenum = ceil($totalnums / $fnum);
-
- // 頁數常量
- @$tmp = $_GET['page'];
-
- //防止惡意翻頁
- if ($tmp > $pagenum)
- echo "<script>window.location.href='index.php'</script>";
-
- //計算分頁起始值
- if ($tmp == "") {
- $num = 0;
- } else {
- $num = ($tmp - 1) * $fnum;
- }
-
- // 查詢語句
- $sql = "SELECT dg_id,dg_username FROM tb_user ORDER BY dg_id DESC LIMIT " . $num . ",$fnum";
- $result = doresult($sql);
-
- // 遍歷輸出
- while (! ! $rows = dolists($result)) {
- echo $rows['dg_id'] . " " . $rows['dg_username'] . "<br>";
- }
-
- // 翻頁鏈接
- for ($i = 0; $i < $pagenum; $i ++) {
- echo "<a href=index.php?page=" . ($i + 1) . ">" . ($i + 1) . "</a>";
- }
- ?>