分页实质就数据库的分段查询
假如每页5条数据,则第一页的数据库查询如下
SELECT * FROM `myguests` limit 0,5
第二页:…limit 5,5
第三页:…limit 10,5
…
第n页:…limit (n-1)*5,5
所以只要获取当前页数,根据当前页数去查询相应数据段即可。
代码实现
index.php
<?php
class ConnectTable{
public function conn(){
$servername = 'localhost';
$username = 'root';
$password = 'root';
$database = 'mytest';
$conn = new MySQLi($servername,$username,$password,$database);
if ($conn->connect_error) {
die('connection faild:'.$conn->connect_error);
} else {
$conn->set_charset('utf8');
return $conn;
}
}
}
$size = 5;
$page = 1;
if (isset($_GET['page']) && intval($_GET['page']) > 0) {
$page = intval($_GET['page']);
}
$table = new ConnectTable();
$conn = $table->conn();
$sql = "SELECT * FROM `myguests` ";
$totalrlt = $conn->query($sql);
//数据总数
$total = $totalrlt->num_rows;
unset($totalrlt);
//分页sql
$sql.= " limit " . ($page - 1)* $size . "," . $size;
$result = $conn->query($sql);
$list = array();
if ($result->num_rows > 0) {
while ( $row = $result->fetch_assoc()) {
$list[] = $row;
}
}
$conn->close();
include ('index.html');
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>page</title>
</head>
<style>
table,tr,td{
border:1px solid gray;
}
ul li {
list-style: none;
}
.pagination>li {
display: inline;
}
</style>
<body>
<table>
<thead>
<tr>
<td>id</td>
<td>name</td>
<td>email</td>
<td>reg_time</td>
</tr>
</thead>
<tbody>
<?php foreach ($list as $item) { ?>
<tr>
<td><?php echo $item['id'] ?></td>
<td><?php echo $item['firstname'] . '.' . $item['lastname']?></td>
<td><?php echo $item['email'] ?></td>
<td><?php echo $item['reg_time'] ?></td>
</tr>
<?php } ?>
</tbody>
</table>
<div>
<ul class="pagination">
<li><span >共 <?php echo $total ?> 条</span></li>
<?php if($page>1){ ?>
<li><a href="index.php?page=<?php echo $page-1 ?>">上一页</a></li>
<?php } ?>
<?php if($page<ceil($total/$size)){ ?>
<li><a href="index.php?page=<?php echo $page+1 ?>">下一页</a></li>
<?php } ?>
</ul>
</div>
</body>
</html>```