PHP实现分页功能

PHP实现分页功能

1.PHP代码块

<?php
header("content-type:text/html;charset=utf8");
$pdo = new  PDO("mysql:host=127.0.0.1;dbname=user;",'root','root');
$resobj=$pdo->query("select * from article");
$data=$resobj->fetchAll(PDO::FETCH_ASSOC);
//页数
$tiaoshu =3;
$count=count($data);
$yeshu=ceil($count/$tiaoshu);

if(isset($_GET['page'])){
    //当前请求的页码
    $page =$_GET['page'];
    if($page<1){
        $page=1;
    }elseif($page>$yeshu){
        $page=$yeshu;
    }
}else{
    $page=1;
}
//拿到页码是不是可以去执行数据库的匹配了 利用offset
//偏移量如何计算出来的  (1-1)*3    (2-1)*3  (3-1)*3
$offset=($page-1)*$tiaoshu;
$sql ="select * from article limit {$tiaoshu} offset $offset";
$resobj=$pdo->query($sql);
$data=$resobj->fetchAll(PDO::FETCH_ASSOC);
foreach ($data as $k=>$v){
    echo "<div>
      <h1>{$v['aname']}</h1>
      <h2>{$v['content']}</h2>
</div>";
}
?>

2.HTML

<html>
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>分页功能</title>
</head>
<body>
<ul>
    <a href="?page=<?=$page-1?>" onclick=""><span>上一页</span></a>
    <?php for ($i=1;$i<=$yeshu;$i++) :  ?>
        <a href="?page=<?=$i?>"><span><?=$i?></span></a>
    <?php endfor; ?>
    <a href="?page=<?=$page+1?>" onclick=""><span>下一页</span></a>
</ul>
</body>
</html>

猜你喜欢

转载自blog.csdn.net/weixin_43708754/article/details/86713883