sql指令的分页
效果
1.建一个名字为myschool的数据库
2.根据自己喜好随机插入几条记录
<?php
/*print_r($_SERVER);*/
//设置北京时间
date_default_timezone_set('PRC');
//预定于变量$_GET,该数组存储的是以get方式请求数据
/*print_r($_GET);*/
const PAGE_SIZE=2; //每页多少条记录
$page = 1;//默认为第1页
if(isset($_GET['page'])){
$page = $_GET['page'];
}
/*echo $page;*/
$conn = @new mysqli('localhost','root','','myschool');
if($conn->connect_error){
die('连接数据库失败');
}
$conn->set_charset('utf8');
//计算记录总数
$sql = "select count(*) from user";
$result = $conn->query($sql);
$date = $result->fetch_row();
$count = $date[0];
//总页数,取整数(ceil,floor,round)
$page_count = ceil($count/PAGE_SIZE);
//page = 1,$index=0;page=2;$index=2;page=3,$index=4
$index = ($page-1)*PAGE_SIZE;
$sql = "select id,user,create_time from user limit $index,".PAGE_SIZE;
$result = $conn->query($sql);
$arr=[];
while($row = $result->fetch_assoc()){
$arr[] = $row;
}
$result->free();
$conn->close();
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<link rel="stylesheet" type="text/css" href="./bootstrap-3.3.7-dist/css/bootstrap.min.css">
<script type="text/javascript" src="./bootstrap-3.3.7-dist/js/jquery-3.3.1.min.js"></script>
<script type="text/javascript" src="./bootstrap-3.3.7-dist/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<div class="panel panel-primary">
<div class="panel-heading">用户列表</div>
<table class="table table-bordered table-striped table-hover">
<tr>
<th>用户名</th>
<th width="250">创建日期</th>
</tr>
<?php foreach($arr as $row) { ?>
<tr>
<td><?php echo $row['user'] ?></td>
<td><?php echo date('Y-m-d H:i:s',$row['create_time']) ?></td>
</tr>
<?php } ?>
</table>
<nav aria-label="...">
<ul class="pager">
<?php if($page-1>0){ ?>
<li><a href="<?php echo $_SERVER['PHP_SELF'] ?> ?page=<?php echo $page-1 ?>">上一页</a></li>
<?php } ?>
<?php if($page+1<=$page_count){ ?>
<li><a href="<?PHP echo $_SERVER['PHP_SELF'] ?> ?page=<?php echo $page+1 ?>">下一页</a></li>
<?php } ?>
</ul>
</nav>
</div>
</div>
</body>
</html>
4.代码中的函数
- date_default_timezone_set
— 设定用于一个脚本中所有日期时间函数的默认时区— 设定用于一个脚本中所有日期时间函数的默认时区 - limit
$sql = “select id,user,create_time from user limit $index,”.PAGE_SIZE;
limit是mysql的语法,select * from table limit m,n。 其中m是指记录开始index,从0开始,表示第一条记录,n是指从第m+1条开始,取n条。
const PAGE_SIZE 计算每页的条数 - _SERVER和_POST一样都是一个数组,也都是系统预定义变量
- PHP_SELF
. 表示当前要访问文件的路径。通常用echo $_SERVER[‘PHP_SELF’]输出路径。在链接中写入,同时执行效果,点击下一页时访问user.php?page=2,点击上一页访问user.php?page=1表示当前要访问文件的路径。通常用echo $_SERVER[‘PHP_SELF’]输出路径。在链接中写入,同时执行效果,点击下一页时访问user.php?page=2,点击上一页访问user.php?page=1 - 预定于变量 GET,该数组存储的是以get方式请求数据
if(isset($_GET[‘page’])){
$page = $_GET[‘page’]; }检查page是否存在,即页数是否存在,为以后访问页面做铺垫 - const PAGE_SIZE 计算每页多少条记录
- 用ceil进行对计算的结果四舍五入
5.实现步骤
- 在html链接上加参数,这样才能给url地址上添加参数,达到跳转页面的效果,同时page也不能写死,要计算出当前页号,我们在php代码中设当前页号为1,在用if求值。我们在html中写了php代码,控制page-1>0,page+1<= page+1<=page+1<=page_count等状况。
- 解决总页数的问题,我们使用select count(*)获取,获取时值只有一行一列,我们使用$result->fetch_row()获取这一行,然后获取数组里的第0列,用总页数除以每页的条数得到页数。
- limit我们也要写活,索引号要计算,当前页号(-1)*每页条数。