分页数据准备代码showpages.php
<?php
namespace staff_table;
use PDO;
$db = new PDO('mysql:dbname=phpedu', 'root', 'root');
$page = $_GET['p'] ?? 1;
echo "当前页: p= $page <br>";
$num = 10;
$sql = 'SELECT COUNT(`id`) AS `total` FROM `staff`';
$stmt = $db->prepare($sql);
$stmt->execute();
$stmt->bindColumn('total',$total);
$stmt->fetch(PDO::FETCH_ASSOC);
echo "总记录数量:$total <br>";
$pages = ceil($total / $num);
echo "总页数: $pages <br>";
$offset = ($page - 1) * $num;
echo "偏移量:$offset <br>";
$sql = "SELECT * FROM `staff` LIMIT $offset,$num";
$stmt = $db->prepare($sql);
$stmt->execute();
$staffs = $stmt->fetchAll(PDO::FETCH_ASSOC);
页面展示分页数据presentation.php
<!DOCTYPE html>
<html lang="en">
<?php
require 'showpages.php'
?>
<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: 400px;
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;
}
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>
<td>ID</td>
<td>姓名</td>
<td>性别</td>
<td>邮箱</td>
</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 for ($i = 1 ; $i <= $pages; $i++) : ?>
<?php
$url = $_SERVER['PHP_SELF'] . '?p=' . $i;
$active = $i == $_GET['p'] ? 'active' : null;
?>
<a href="<?= $url ?>" class="<?= $active ?>"><?= $i ?></a>
<?php endfor ?>
</p>
</body>
</html>