PHP实现数据库数据的分页

一、实现思路:

1. 使用bootstrap框架,实现数据库的连接,以及sql指令的执行;

2.写html中的table代码,用bootstrap中的表格样式进行修饰;

3.在分页的链接上添加参数;

4.获得当前的页号;

5.控制翻页(向上不得超过第一页,向下不得超过最后一页);

6.获得总页数;

7.求得总页数;

8.求得每一页开始的第一条数据的索引号;

二、举个例子吧:连接本地myschool数据库

<?php
header("content-type:text/html;charset=utf-8");
//设置时间为北京时间
date_default_timezone_set('PRC');
//预定义变量$_GET,该数组存储的是以get方式存储的数据
const PAGE_SIZE = 2;//每页多少条记录
$page = 1;//默认为第一页
if(isset($_GET['page'])){
	$page = $_GET['page'];
}
//连接数据库
$conn = @new mysqli("localhost",'root','','mysclool');
//检测数据库是否连接成功
if($conn -> connect_error){
	die("数据库连接失败");
}
//设置编码格式
$conn -> set_charset('utf8');

//获取数据库中的表有多少行
$sql = "select count(*) from user";
//执行sql语句
$res = $conn -> query($sql);
//判断能写几页
$length = $res ->fetch_row();
$count = $length[0];
$len = ceil($count/PAGE_SIZE);
//每次从第几个索引开始
$index = ($page-1)*PAGE_SIZE;
//创建sql指令 实现每页返回特定的数据量
$sql = "select id,user,create_time from user limit $index,".PAGE_SIZE;
//执行sql指令
$res = $conn -> query($sql);
// print_r($res);
// exit;
//检测sql指令是否正确
if($res === false){
	die("执行sql指令出错");
}
//获取结果集
$arr = [];
while($row = $res -> fetch_assoc()){
	$arr[] = $row;
}
//释放结果集
$res -> 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="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 panel-heading">用户信息表</div>
		<table class="table table-bordered table-striped table-hover">
			<tr>
				<td>用户名</td>
				<td width="200">创建日期</td>
			</tr>
            //使用foreach循环向表格中添加数据
			<?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 <=$len){ ?>
				<li><a href="<?php echo $_SERVER['PHP_SELF'] ?>?page=<?php echo $page+1 ?>">下一页</a></li>
			<?php } ?>
			</ul>
		</nav>
	</div>
</div>
</body>
</html>

注意:1.逻辑思维能力要好,清楚下一步该做什么;

            2.$_GET、$_SERVER的使用;

            3.要关闭数据库连接,以及释放结果集;

猜你喜欢

转载自blog.csdn.net/weidandan520/article/details/84376437