分页代码如下
<?php
require '../demo01/model.php';//导入连接数据库的代码
$page=isset($_GET['p'])? $_GET['p']:1;//定义变量由浏览器传入
$sql = "select * from test limit ".($page-1) * 5 .",5 ";//查询语句,limit后的两个参数第一个是查询的起始位置,第二个是显示的数据条数
$result=mysqli_query($conn,$sql);
echo "<table border=1 cellpadding=5 cellspacing=0 align='center' width='15%'>";
echo "<tr> <td>id</td> <td>name</td> <td>sex</td> </tr>";
while ($rows=mysqli_fetch_assoc($result)){
echo"<tr>";
echo "<td>{$rows['id']}</td>";
echo "<td>{$rows['name']}</td>";
echo "<td>{$rows['sex']}</td>";
echo "</tr>";
}
echo "</table>";//循环输出数据
mysqli_free_result($result);
$to_sql="SELECT COUNT(*)FROM test";
$result= mysqli_query($conn,$to_sql);
$row=mysqli_fetch_array($result);
$count=$row[0];
$to_pages=ceil($count/5);
if($page<=1){
echo "<a href='".$_SERVER['PHP_SELF']."?p=1'>上一页</a>";
}else{
echo "<a href='".$_SERVER['PHP_SELF']."?p=".($page-1)."'>上一页</a>";
}
if ($page<$to_pages){
echo "<a href='".$_SERVER['PHP_SELF']."?p=".($page+1)."'>下一页</a>";
}else{
echo "<a href='".$_SERVER['PHP_SELF']."?p=".($to_pages)."'>下一页</a>";
}
?>
效果如图所示:
点击下一页后:page值变为2