评论

收藏

[PHP] php实现超简的分页功能

开发技术 开发技术 发布于:2023-03-15 13:47 | 阅读数:276 | 评论:0


代码案例来自吾爱破解论坛
效果如下:
QQ截图20230315134459.jpg

PHP代码:
<?php
try {
  $dsn = "mysql:host=localhost;dbname=数据库名";
  $username = "数据库名";
  $password = "数据库密码";
  $pdo = new PDO($dsn, $username, $password);
} catch(PDOException $e) {
  echo "Connection failed: " . $e->getMessage();
}
 
//计算总记录数
$total=$pdo->query('SELECT COUNT(1) FROM `表名`')->fetchColumn();
//每页显示记录数
$pageSize=10;
//计算总页数
$pageCount=ceil($total/$pageSize);
//当前页码,默认为第一页
$pageNum=isset($_GET['page']) ? $_GET['page'] : 1;
//起始记录数
$start=($pageNum-1)*$pageSize;
//查询分页数据
$sql="SELECT * FROM `表名` LIMIT {$start},{$pageSize}";
$stmt=$pdo->query($sql);
$list=$stmt->fetchAll(PDO::FETCH_ASSOC);
?>
HTML代码:
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>PHP+Layui分页</title>
  <link rel="stylesheet" >
</head>
<body>
<div class="layui-container">
  <br>
  <br>
  <center>
  <h3>超简单php+layui分页</h3>
  </center>
  <table class="layui-table">
  <thead>
  <tr>
    <th>ID</th>
    <th>产品名</th>
    <th>产品库存</th>
    <th>操作</th>
  </tr>
  </thead>
  <tbody>
  <?php foreach($list as $vo){ ?>
    <tr>
    <td><?php echo $vo['id']; ?></td>
    <td>产品<?php echo $vo['id']; ?></td>
    <td>库存<?php echo $vo['id']; ?></td>
    <td><a href=delete.php?id=<?php echo $vo['id']; ?>  </a>删除</td>
    </tr>
  <?php } ?>
  </tbody>
  </table>
  <div id="demo"></div>
</div>
<script src="https://cdn.staticfile.org/layui/2.5.6/layui.min.js"></script>
<script>
  layui.use(['laypage'], function(){
  var laypage = layui.laypage;
  laypage.render({
    elem: 'demo',
    count: <?php echo $total; ?>,
    limit: <?php echo $pageSize; ?>,
    curr: <?php echo $pageNum; ?>,
    jump: function(obj,first){
    if(!first){
      window.location.href = '?page='+obj.curr;
    }
    }
  });
  });
</script>
</body>
</html>

关注下面的标签,发现更多相似文章