代码
<?php
header("Content-type:text/html;charset=utf-8");
//传入页码
$p = $_GET["p"];
//每页数量
$pageSize = 1;
//链接数据库
$host = "localhost";
$user = "root";
$pass = "";
$db = "test";
$conn = mysqli_connect($host, $user, $pass);
if (!$conn) {
echo "失败";
exit;
}
mysqli_select_db($conn, $db);
//分页查询mysql语句
$sql = "SELECT * FROM user LIMIT " . ($p - 1) * $pageSize . ",$pageSize";
//总记录数mysql语句
$count = "SELECT count(*) FROM user";
$total_result = mysqli_fetch_row(mysqli_query($conn, $count));
//总记录数
$total = $total_result["0"];
//数据集
$result = mysqli_query($conn, $sql);
echo "<table border='1' cellspacing='0'>";
//循环打印数据
while ($row = mysqli_fetch_assoc($result)) {
echo "<tr><td>{$row['id']}</td><td>{$row['name']}</td></tr>";
}
echo "</table>";
mysqli_free_result($result);
mysqli_close($conn);
/*显示数据+分页条*/
//计算最后一页
$total_page = ceil($total / $pageSize);
$pageStyle = "";
//如果大于1 就显示首页 上一页
if ($p > 1) {
$pageStyle .= "<a href='" . $_SERVER['PHP_SELF'] . "?p=1'>首页</a>";
$pageStyle .= "<a href='" . $_SERVER['PHP_SELF'] . "?p=" . ($p - 1) . "'>上一页</a>";
}
/*每次显示5个页码的逻辑*/
//初始化
$showPage = 5;
//计算偏移量
$pageoffset = ($showPage - 1) / 2;
$start = 1;
$end = $total_page;
//总页数大于显示的页数
if ($total_page > $showPage) {
//当前页大于偏移量+1 显示省略号
if ($p > $pageoffset + 1) {
$pageStyle .= "<a>...</a>";
}
//当前页大于偏移量 显示开始位置 和结束位置
if ($p > $pageoffset) {
//当前页减去 偏移量 显示开始位置
$start = $p - $pageoffset;
//如果最后一页大于当前页加上偏移量 就显示当前页+偏移量的页面 否则就是显示最后一页
$end = $total_page > $p + $pageoffset ? $p + $pageoffset : $total_page;
} else {
//当前页小于偏移量
//起始位置
$start = 1;
//结束位置
$end = $total_page > $showPage ? $showPage : $total_page;
}
//当前页+偏移量大于最后一页
if ($p + $pageoffset > $total_page) {
$start = $start - ($p + $pageoffset - $end);
$end = $total_page;
}
}
//循环显示分页
for ($i = $start; $i <= $end; $i++) {
if($i == $p){
$pageStyle .= "<a style='color:red;font-size:20px' href='" . $_SERVER['PHP_SELF'] . "?p=" . $i . "'>{$i}</a>";
}else{
$pageStyle .= "<a href='" . $_SERVER['PHP_SELF'] . "?p=" . $i . "'>{$i}</a>";
}
}
//如果总页数大于显示的页数 并且 最后一页大于当前页+偏移量
if ($total_page > $showPage && $total_page > $p + $pageoffset) {
$pageStyle .= "<a>...</a>";
}
//如果不等于最后一页 就显尾页 下一页
if ($p != $total_page) {
$pageStyle .= "<a href='" . $_SERVER['PHP_SELF'] . "?p=" . ($p + 1) . "'>下一页</a>";
$pageStyle .= "<a href='" . $_SERVER['PHP_SELF'] . "?p=" . $total_page . "'>尾页</a>";
}
$pageStyle .= "<span>共有{$total}条数据</span>";
//显示分页
echo $pageStyle;