在MK网学习课程做的案例,非常简陋,主要是熟悉语言吧,初步进行学习的总结,先在数据库随便建个100来条数据的表
<?php
header("content-type:text/html;charset=utf-8");
//设置字符集
$page = $_GET['id'];
//GET传入的分页id,在url输入时加上?id=4(页码内的数)
$mysqli = new mysqli('localhost','root','199486','article');
//使用mysqli扩展连接数据库
if($mysqli->connect_errno){
echo "错误信息为:".$mysqli->connect_error;
}
//若连接错误,得到错误信息
$sql = "SELECT * FROM page LIMIT ".(($page-1)*10).",10";
//限制每页数据为10条
$mysqli_result = $mysqli->query($sql);
//执行查询,得到$mysqli_result对象
//print_r($mysqli_result);
while($row = $mysqli_result->fetch_assoc()){
$rows[] =$row;
//通过循环每次取出一条关联数据,放入$rows数组
}
$sql_count = "SELECT COUNT(*) FROM page";
//得到数据表数据总数
$mysqli_result = $mysqli->query($sql_count);
$row = $mysqli_result->fetch_array();
//print_r($row);
$total = $row[0];
$total_page = ceil($total/10);
//得到总页数
$p1 = $page - 1;
$p2 = $page + 1;
//上下页的URL传参
$start = 1;
$end = $total_page;
//初始化开始,结束页
$show_page = 5;
//页面显示数字按钮数
$offset_page = ($show_page-1)/2;
//点击按钮左右按钮的数量
$page_banner = "";
//通过字符串拼接分页
if($page > 1){
$page_banner.= "<li><a href='".$_SERVER['PHP_SELF']."?id=1'>首页</a></li>";
$page_banner.= "<li><a href='".$_SERVER['PHP_SELF']."?id=$p1'>上一页</a></li>";
}
//页数大一1才显示首页和上一页
if($total_page > $show_page){
//先判断总页数与显示页数的关系
if($page>$offset_page){
//开始的页码为页数减去偏移量
$start = $page - $offset_page;
$end = $total_page>$page+$offset_page?$page+$offset_page:$total_page;
}else{
$start = 1;
$end = $show_page;
}
if($page+$offset_page>$total_page){
$start = $start - ($page + $offset_page - $total_page);
}
}
for($i = $start;$i<=$end;$i++){
$page_banner .="<li><a href='".$_SERVER['PHP_SELF']."?id=$i'>$i</a></li>";
}
if($page < $total_page){
$page_banner.="<li><a href='".$_SERVER['PHP_SELF']."?id=$p2'>下一页</a></li>";
$page_banner.= "<li><a href='".$_SERVER['PHP_SELF']."?id=$total_page'>尾页</a></li>";
}//页数小于总页数才显示尾页和下一页
$page_banner.="<li>共{$total_page}页</li>";
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
<link rel="stylesheet" href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css"
integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
</head>
<body>
<table class="table table-striped">
<?php foreach ($rows as $row):?>
<tr>
<td><?php echo $row['id']; ?></td>
<td><?php echo $row['username']; ?></td>
</tr>
<?php endforeach;?>
</table>
<ul class="pagination">
<?php echo $page_banner;?>
</ul>
</body>
</html>