簡單分頁類分享 現(xiàn)在公布一個簡單分類制作。只要理解了這個類的原理和步驟,其他復雜類也就能夠觸類旁通了。不廢話,直接上源碼,可以直接用在你的項目中。
數(shù)據(jù)庫操作類代碼:mysqli.func.php
- <?php
- // 數(shù)據(jù)庫連接常量
- define('DB_HOST', 'localhost');
- define('DB_USER', 'root');
- define('DB_PWD', '');
- define('DB_NAME', 'guest');
-
- // 連接數(shù)據(jù)庫
- function conn()
- {
- $conn = mysqli_connect(DB_HOST, DB_USER, DB_PWD, DB_NAME);
- mysqli_query($conn, "set names utf8");
- return $conn;
- }
-
- //獲得結(jié)果集
- function doresult($sql){
- $result=mysqli_query(conn(), $sql);
- return $result;
- }
-
- //結(jié)果集轉(zhuǎn)為對象集合
- function dolists($result){
- return mysqli_fetch_array($result, MYSQL_ASSOC);
- }
-
- function totalnums($sql) {
- $result=mysqli_query(conn(), $sql);
- return $result->num_rows;
- }
-
- // 關(guān)閉數(shù)據(jù)庫
- function closedb()
- {
- if (! mysqli_close()) {
- exit('關(guān)閉異常');
- }
- }
-
- ?>
分頁實現(xiàn)代碼:- <?php
- include 'mysqli.func.php';
-
- // 總記錄數(shù)
- $sql = "SELECT dg_id FROM tb_user ";
- $totalnums = totalnums($sql);
-
- // 每頁顯示條數(shù)
- $fnum = 8;
-
- // 翻頁數(shù)
- $pagenum = ceil($totalnums / $fnum);
-
- // 頁數(shù)常量
- @$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>";
- }
- ?>