【前言】
? ?本文总结下PHP实现分页的原理和方法,具体分析在代码里已经注释过,直接看代码。
? ?相关知识点,我在上篇文章做了总结
? ?注意文件名
class="page.php" name="code"><meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<?php
//连接user数据库
include 'config.php';
$connect = mysqli_connect(DB_HOST,DB_USER,DB_PWD,DB_NAME);
if(!$connect){
die("could not connect:".mysqli_error());
}else{
echo "连接成功<br>";
//查询结果
// mysqli_query() 函数执行一条 MySQL 查询
$result = mysqli_query($connect,"select* from user");
//mysqli_num_rows结果集里行数,该结果集从 mysql_query() 的调用中得到
$count = mysqli_num_rows($result);
//传页的话改为整型
$page = isset($_GET['page'])?(int)$_GET['page']:1;
//每页显示数
$num = 5 ;
//总页数
$total = ceil($count / $num);
if ($page<1) {
$page = 1;
}
if ($page>$total) {
$page = $total;
}
//偏移量
$offset = ($page-1)*$num;
$sql = "select id,name,age from demo order by id asc limit $offset,$num";
$result = mysqli_query($connect,$sql);
if ($result&&mysqli_num_rows($result)) {
echo "<table border=1 cellspacing=0>";
while($row = mysqli_fetch_array($result)){
echo "<tr>";
echo "<td>".$row['id']."</td>";
echo "<td>".$row['name']."</td>";
echo "<td>".$row['age']."</td>";
echo "<tr/>";
}
echo'<tr>
<td colspan="5">
<a href="page.php?page=1">首页</a>
<a href="page.php?page=' .($page-1). '">上一页</a>
<a href="page.php?page=' .($page+1). '">下一页</a>
<a href="page.php?page=' .$total. '">尾页</a>
当前是第'.$page.'页 共'.$total.'页
</td>
</tr>';
echo "</table>";
}else{
echo "没有数据";
}
}
//关闭连接
$close = mysqli_close($connect);
if(!$close){
die("关闭数据库失败");
}else{
echo "关闭成功";
}
?>
?
? ?配置文件
<?php //数据库服务器 define('DB_HOST', 'localhost'); //数据库用户名 define('DB_USER', 'root'); //数据库密码 define('DB_PWD', 'root'); //数据库名 define('DB_NAME', 'user'); //字符集 define('DB_CHARSET', 'utf8'); ?>
?
效果图如下:
?
?
?
?
?
.