<?php
header('content-type:text/html;charset=utf-8');
// 连接数据库
$con = mysqli_connect('127.0.0.1','root','root','student') or die('链接数据库失败'.mysqli_error());
mysqli_query($con,'set names utf8');
// 从数据库获取数据
$count = "select count(*) as total from student";
$res = mysqli_query($con,$count);
$row = mysqli_fetch_assoc($res);
$total = $row['total'];
// 设置每页显示条数
$pageSize = 10;
// 总页数
$pages = ceil($total/$pageSize);
// 设置当前页
$curpage = isset($_GET['page'])? intval($_GET['page']):1;
if ($curpage<=0) {
$curpage=1;
}
if ($curpage>$pages) {
$curpage = $pages;
}
$show = ($curpage-1)*$pageSize;
// 每页显示的内容
$sql = "select * from student limit $show,$pageSize";
$result = mysqli_query($con,$sql);
$arr = array();
while($row = mysqli_fetch_assoc($result)){
$arr[] = $row;
}
$start = 1;
$end = $pages;
if ($curpage<=5) {
$start = 1;
$end = $end < 10? $end : 10;
}else{
$end = $curpage + 5 > $end? $end : $curpage + 5;
$start = $end - 9 < 0? 1:$end - 9;
}
$pagess = '';
for ($i=$start; $i <= $end; $i++) {
if ($curpage == $i) {
$pagess .= "<a class='page' href='page.php?page={$i}' style='color:red;'>{$i}</a> ";
}
else{
$pagess .= "<a class='page' href='page.php?page={$i}'>{$i}</a> ";
}
}
// 首页
$head = "<a href='page.php?page=1'>首页</a>";
//上一页
$ye = $curpage-1<=0?1:$curpage-1;
$prev = "<a href='page.php?page=$ye'>上一页</a>";
//下一页
$ye1 = $curpage+1>$pages?$pages:$curpage+1;
$next = "<a href='page.php?page=$ye1'>下一页</a>";
// 尾页
$foot = "<a href='page.php?page=$pages'>尾页</a>";
//
$pagess = $head.$prev.$pagess.$next.$foot;
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>分页的实现</title>
<style>
a{
display: inline-block;
text-decoration: none;
font-size: 13px;
color:#111;
}
a:hover{
background-color: #00FFFF;
}
.pg{
text-align: center;
}
.page{
width: 30px;
height: 30px;
line-height: 30px;
text-align: center;
margin-top: 10px;
margin-left: 1x;
border: 1px solid #444;
}
</style>
</head>
<body>
<table border="1px" align="center" cellpadding="0" cellspacing="0" width="800" height='500px'>
<caption><h2>学生基本信息管理</h2></caption>
<tr><th>id</th><th>姓名</th><th>年龄</th><th>性别</th></tr>
<?php foreach ($arr as $val): ?>
<tr>
<td align='center'><?php echo $val['id'];?></td>
<td align='center'><?php echo $val['name'];?></td>
<td align='center'><?php echo $val['age']; ?></td>
<td align='center'><?php echo $val['sex'];?></td>
</tr>
<?php endforeach; ?>
</table>
<div class="pg"><?php echo $pagess ?></div>
</body>
</html>
php+mysql实现主流分页
最新推荐文章于 2022-10-25 22:52:19 发布
本文详细讲解如何利用PHP与MySQL数据库配合,实现主流的分页功能。通过优化SQL查询,使用LIMIT和OFFSET来高效获取分页数据,同时讨论了如何处理大数量数据的分页问题,确保性能和用户体验。
摘要由CSDN通过智能技术生成