php下的分頁原理學習
阿新 • • 發佈:2018-01-28
art 查詢 鏈接 ror www. 不可 生成 path count
**首先確定分頁需要確定的參數數據**
`page 當前頁碼`
`pageSize 每一頁的條數`
`total_count 總共的數據條數`
`pageNumber = ceil ( totalCount / pageSize) 總共可以分為幾頁`
begin :
**1.首先需要正確的連接數據庫查詢下總條數信息**
//配置數據庫信息 $host = "localhost:3306"; $username = "root"; $password = "";//密碼 $db = "";//表名 //創建數據庫鏈接 $conn = mysqli_connect($host, $username, $password, $db); if (!$conn) { echo "connect error"; exit; } if ($result = mysqli_query($conn, "SELECT COUNT(*) FROM 表名")) { $row = mysqli_fetch_assoc($result); $total_count = $row[‘COUNT(*)‘];//獲得總共的數據條數 }
php5.5 以後廢棄了之前的mysql_XXX的 api 操作 改用 mysqli_XXX的 api;
**2.判斷邊界條件生成sql語句**
`sql`語句:`"SELECT * FROM 表名 LIMIT 起始位置,數量"`
//獲得www.domain.com/xxx/xxx?page=num;url的參數 $page = $_GET[‘page‘]; //總共可分的頁數 $pageNumber = ceil($total_count / $pageSize); if ($page <= 0 || $page > $pageNumber ) { echo ‘404‘;//非法的page參數直接返回404 exit; } else { $start = ($page - 1) * 10; } if($result = mysqli_query($conn, "SELECT * FROM 表名 LIMIT $start,10")){ while ($row = mysqli_fetch_assoc($result)) { echo $row[‘id‘], ‘ ‘, $row[‘name‘], "<br/>"; //查詢出結果 } }
**3.前端分頁的顯示和url**
//邊界條件判定來確定 `上一頁` `下一頁` 按鈕的顯示和是否可以點擊; -1表示無效,即不可點擊 if ($page <= 1) { $pre = -1; } else { $pre = $page - 1; } if ($page < $pageNumber) { $next = $page + 1; } else { $next = -1; } $path = $_SERVER["PHP_SELF"]; if ($pre == -1) { echo "<span class=‘pagination‘>上一頁</span>"; } else { echo "<a class=‘pagination‘ href=‘$path?page=$pre‘>上一頁</a>"; } if ($page == 1) { echo "<span class=‘pagination‘>首頁</span>"; } else { echo "<a class=‘pagination‘ href=‘$path?page=1‘>首頁</a>"; } //分頁頁碼按鈕的顯示邏輯 // $paginationSize= 5; //默認顯示5個連續的可點擊分頁頁碼按鈕 //頁碼數量超過一定數值後顯示前兩頁 if (($page + $paginationSize) > $next_limit) { $end_page = $next_limit; } else { $end_page = $page + $paginationSize; } if ($page > 4) { echo "<a class=‘pagination‘ href=‘$path?page=1‘>1</a>"; echo "<a class=‘pagination‘ href=‘$path?page=2‘>2</a>"; echo "<span class=‘point‘>···</span>"; } for ($i = $end_page - $paginationSize; $i <= $end_page; $i++) { if ($i == $page) { echo "<span class=‘pagination‘>$i</span>"; } else { echo "<a class=‘pagination‘ href=‘$path?page=$i‘>$i</a>"; } } if ($page == $next_limit) { echo "<span class=‘pagination‘>尾頁</span>"; } else { echo "<a class=‘pagination‘ href=‘$path?page=$next_limit‘>尾頁</a>"; } if ($next == -1) { echo "<span class=‘pagination‘ >下一頁</span>"; } else { echo "<a class=‘pagination‘ href=‘$path?page=$next‘>下一頁</a>"; }
end:
完整代碼:
[github][1]
[1]: https://github.com/llauser/hand-demo/tree/master/php
php下的分頁原理學習