仿PHP中文网分页
<?php
require 'page_refer.php' ;
// $pageChange = createPages()
// use PDO;
// 连接
$db = new PDO('mysql:dbname=phpedu', 'root', 'root');
// 1. 页数
$page = $_GET['p'] ?? 1;
// 2. 数量
$num = 5;
// 3. 偏移量 = (页数 - 1) * 数量
$offset = ($page - 1) * $num;
// 4. 计算总记录数
$sql = 'SELECT COUNT(*) AS `total` FROM `staff`';
$stmt = $db->prepare($sql);
$stmt->execute();
// 将总数量绑定到一个变量上
$stmt->bindColumn('total', $total);
$stmt->fetch();
$sql = <<< SQL
SELECT *
FROM `staff`
LIMIT $offset, $num;
SQL;
$stmt = $db->prepare($sql);
$stmt->execute();
$staffs = $stmt->fetchAll(PDO::FETCH_ASSOC);
// 表示第5页, 一共有20页
$page = $_GET['page'] ?? 1;
$pagelist = createPages($page, 20);
?>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>分页展示数据</title>
<style>
table {
width: 500px;
border-collapse: collapse;
text-align: center;
}
table th,
table td {
border: 1px solid;
padding: 5px;
}
table thead {
background-color: lightcyan;
}
table caption {
font-size: larger;
margin-bottom: 8px;
}
body>p {
display: flex;
}
p>a {
text-decoration: none;
color: #555;
border: 1px solid;
padding: 5px 10px;
margin: 10px 2px;
}
.active {
background-color: seagreen;
color: white;
border: 1px solid seagreen;
}
</style>
</head>
<body>
<table>
<caption>员工信息表</caption>
<thead>
<tr>
<th>ID</th>
<th>姓名</th>
<th>性别</th>
<th>邮箱</th>
</tr>
</thead>
<tbody>
<?php foreach ($staffs as $staff) :extract($staff) ?>
<tr>
<td><?=$id?>
</td>
<td><?=$name?>
</td>
<td><?=$sex?>
</td>
<td><?=$email?>
</td>
</tr>
<?php endforeach ?>
</tbody>
</table>
<p>
<?php $url = 'http://phpedu.io/0819/demo4.php?page=' ?>
<?php foreach ($pagelist as $staff) : ?>
<?php if(isset($staff)): ?>
<a href="<?php echo $url . $staff; ?>"<?php echo $page == $staff ? 'class="active"' : null ?>><?=$staff ?></a>
<?php else: ?>
<a>......</a>
<?php endif ?>
<?php endforeach ?>
<!-- <?php for ($i=1; $i <= $pages; $i++): ?> -->
<?php
// 实现页码高亮
$page = $_GET['p'] ?? 1;
$active = ($i == $page) ? 'active' : null;
?>
<!-- <a href="<?=$url?>"
class="<?=$active?>"><?=$i?></a> -->
<?php endfor ?>
<br>
</p>
</body>
</html>