代码如下:
<!doctype html> <html lang="en"> <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"> <link rel="stylesheet" href="../css/bootstrap.css"> <script src="../js/jquery-3.2.1.js"></script> <script src="../js/bootstrap.js"></script> <title>分页显示用户信息表</title> </head> <body> </body> </html> <?php /** * 数据表分页功能 */ header('Content-Type:text/html; charset=UTF-8'); $page = isset($_GET['p'])?$_GET['p']:1; //页数 $page = ($page == 0)? 1:$page; $num = 5; //设置每页显示5条数据 $offset = ($page-1)*$num; //计算偏移量 //1、获取所有数据,并用表格显示出来 $pdo = new PDO('mysql:dbname=demo1','root','root'); //创建pdo对象,连接数据库 $sql = "SELECT `id`,`name`,`email` FROM `user` LIMIT :offset,:num"; //创建查询SQL语句 $pdoStmt = $pdo->prepare($sql); //创建pdoStatment对象 //绑定参数 $pdoStmt->bindParam('offset',$offset,PDO::PARAM_INT); $pdoStmt->bindParam('num',$num,PDO::PARAM_INT); //执行查询,并将返回结果存入变量$res $res = $pdoStmt->execute(); //制作表格,显示查询出的数据 echo '<h3>用户信息表</h3>'; echo '<table class="table table-hover table-bordered text-primary" style="width: 50%;text-align: center">'; echo '<tr><td>ID</td><td>用户名</td><td>邮箱</td></tr>'; foreach ($pdoStmt as $row){ echo '<tr>'; echo '<td>'.$row['id'].'</td><td>'.$row['name'].'</td><td>'.$row['email'].'</td>'; echo '</tr>'; } echo '</table>'; //2、添加分页标签 //计算一共有多少页 $pdoStmt2 = $pdo->prepare("SELECT * FROM `user`"); $pdoStmt2->execute(); $totalPage = ceil($pdoStmt2->rowCount() / $num); //制作分页 echo '<div>'; echo '<nav>'; echo '<ul>'; echo '<li><a href="http://localhost/30/page.php?p=1"><span aria-hidden="true">首页</span></a></li>'; echo '<li><a href="http://localhost/30/page.php?p='; echo (($page-1)==0)?1:($page-1); echo '" aria-label="Previous"><span aria-hidden="true">«</span></a></li>'; for ($i=1;$i<=$totalPage;$i++){ echo '<li><a href="http://localhost/30/page.php?p='.$i.'">'.$i.'</a></li>'; } $page = ($page == $totalPage)?($totalPage-1):$page; // 如果$page等于总页数,则将$page设置为总页数减一,用于避免下一页溢出 echo '<li><a href="http://localhost/30/page.php?p='.($page+1).'" aria-label="Next"><span aria-hidden="true">»</span></a></li>'; echo '<li><a href="http://localhost/30/page.php?p='.$totalPage.'"><span aria-hidden="true">尾页</span></a></li>'; echo '</li>'; echo '</ul>'; echo '</nav>'; echo '</div>'; ?> <script> document.getElementsByTagName('li')[<?php echo ($_GET['p']+1); ?>].className='active' </script>