分页PHP

<?php
//1、连接数据库
$link = mysqli_connect('127.0.0.1','root','root','1906');
//2、设置字符集
mysqli_set_charset($link,'utf8');

 

//接收当前页
$page = isset($_GET['page']) ? $_GET['page'] : 1;
//设置每页显示的条数
$len = 3;
//求出总条数
$sql = "select * from users";
$res = mysqli_query($link,$sql);
$count = mysqli_num_rows($res);
//总页数
$last_page = ceil($count/$len);
//求出偏移量=(当前页-1)*每页的条数
$limit = ($page-1)*$len;
//查询
$sql = "select * from users limit $limit,$len";
$res = mysqli_query($link,$sql);
$data = mysqli_fetch_all($res,1);

//释放结果集
//关闭数据库
?>

<table>
<tr>
<th>主键id</th>
<th>学生姓名</th>
<th>学生性别</th>
<th>学生年龄</th>
<th>学生头像</th>
</tr>

<?php foreach ($data as $k=>$v){ ?>
<tr>
<th><?php echo $v['id']?></th>
<th><?php echo $v['name']?></th>
<th><?php echo $v['sex']==1?'男':'女' ?></th>
<th><?php echo $v['age']?></th>
<th><img src="<?php echo $v['img']?>" width="100" height="100"></th>
</tr>
<?php } ?>
</table>

<?php
echo "<a href='?page=1'>".'|<'."</a> "; // 第一页

for ($i=1; $i<=$last_page; $i++) {
echo "<a href='?page=".$i."'>".$i."</a> ";
};
echo "<a href='?page=$last_page'>".'>|'."</a> "; // 最后一页
?>

posted @ 2021-06-11 19:29  王越666  阅读(41)  评论(0编辑  收藏  举报