範例程式碼如下:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>使用者列表</title> </head> <body> <?php $con = mysqli_connect("localhost","root",""); mysqli_query("set names utf8"); mysqli_select_db("zhiye",$con); $pageSize = 1; //每頁顯示的數量 $rowCount = 0; //要從資料庫中獲取 $pageNow = 1; //當前顯示第幾頁 //如果有pageNow就使用,沒有就預設第一頁。 if (!empty($_GET['pageNow'])){ $pageNow = $_GET['pageNow']; } $pageCount = 0; //表示共有多少頁 $sql1 = "select count(id) from user"; $res1 = mysqli_query($sql1); if($row1=mysqli_fetch_row($res1)){ $rowCount = $row1[0]; } //計算共有多少頁,ceil取進1 $pageCount = ceil(($rowCount/$pageSize)); //使用sql語句時,注意有些變數應取出賦值。 $pre = ($pageNow-1)*$pageSize; $sql2 = "select * from user limit $pre,$pageSize"; $res2 = mysqli_query($sql2); while($row=mysqli_fetch_assoc($res2)){ echo $row['user_name']."<br>"; echo $row['name']."<br>"; echo $row['email']."<br>"; echo $row['password']."<br>"; echo $row['tel']."<br>"; } for ($i=1;$i<=$pageCount;$i++){ echo "<a href='userList.php?pageNow=$i'>$i</a> "; }?> </body> </html>
當有大量資料時,就不能使用上述方法
<?php $con = mysqli_connect("localhost","root",""); mysqli_query("set names utf8"); mysqli_select_db("zhiye",$con); $pageSize = 1; //每頁顯示的數量 $rowCount = 0; //要從資料庫中獲取 $pageNow = 1; //當前顯示第幾頁 //如果有pageNow就使用,沒有就預設第一頁。 if (!empty($_GET['pageNow'])){ $pageNow = $_GET['pageNow']; } $pageCount = 0; //表示共有多少頁 $sql1 = "select count(id) from user"; $res1 = mysqli_query($sql1); if($row1=mysqli_fetch_row($res1)){ $rowCount = $row1[0]; } //計算共有多少頁,ceil取進1 $pageCount = ceil(($rowCount/$pageSize)); //使用sql語句時,注意有些變數應取出賦值。 $pre = ($pageNow-1)*$pageSize; $sql2 = "select * from user limit $pre,$pageSize"; $res2 = mysqli_query($sql2); //$sql = "select * from user"; //$res = mysqli_query($sql,$con); while($row=mysqli_fetch_assoc($res2)){ echo $row['user_name']."<br>"; echo $row['name']."<br>"; echo $row['email']."<br>"; echo $row['password']."<br>"; echo $row['tel']."<br>"; } if($pageNow>1){ $prePage = $pageNow-1; echo "<a href='userList.php?pageNow=$prePage'>pre</a> "; } if($pageNow<$pageCount){ $nextPage = $pageNow+1; echo "<a href='userList.php?pageNow=$nextPage'>next</a> "; echo "當前頁{$pageNow}/共{$pageCount}頁"; } echo "<br/><br/>"; ?> <form action="userList.php"> <input type="text" name="pageNow"> <input type="submit" value="GO"> </form>
更過相關問題請存取PHP中文網:PHP視訊教學
以上就是PHP實現資料分頁顯示詳細操作的詳細內容,更多請關注TW511.COM其它相關文章!