Correction status:Uncorrected
Teacher's comments:
<?php $pdo = new PDO("mysql:host=127.0.0.1;dbname=guest","root","123456"); //每页显示记录数 $PerNum = 5; //当前页数 $page = isset($_GET['p']) ? $_GET['p'] :1; $StartNum = ($page-1)*$PerNum; $sql = "SELECT G_ID,G_UserName,G_Sex,G_Email,G_QQ FROM g_users LIMIT $StartNum,$PerNum"; $stmt = $pdo->prepare($sql); $stmt->execute(); $rows = $stmt->fetchAll(PDO::FETCH_ASSOC); //获取总记录数 $stmt = $pdo->prepare("SELECT COUNT(*) FROM g_users"); $stmt->execute(); $total = $stmt->fetchColumn(0); //计算总页数,ceil()向上取整 $num = ceil($total/$PerNum); ?> <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>分页</title> <style> table,th,td{ border:1px solid #111; } table{ width:70%; height:300px; margin:30px auto; border-collapse:collapse; } table caption{ font-size:2em; margin:30px auto; } table tr:first-child{ height:50px; background:lightblue; } table tr{ text-align:center; } table tr td{ padding:5px; } h2{ text-align:center; } h2 span{ font-size:20px; } h2 a{ text-decoration:none; font-size:20px; display:inline-block; border:1px solid #ccc; width:60px; height:30px; background-color:lightskyblue; color:#000; font-weight:normal; } a:hover{ background-color:green; color:white; font-weight:bold; } form{ display:inline-block; } </style> </head> <body> <table> <caption>用户信息表</caption> <tr> <th>id</th> <th>用户名</th> <th>性别</th> <th>邮箱</th> <th>QQ</th> </tr> <?php foreach ($rows as $row){?> <tr> <td><?php echo $row['G_ID']?></td> <td><?php echo $row['G_UserName']?></td> <td><?php echo $row['G_Sex']?></td> <td><?php echo $row['G_Email']?></td> <td><?php echo $row['G_QQ']?></td> </tr> <?php }?> </table> <h2><span>共查询到<?php echo $total;?>条记录</span> <?php if($page>1){?><!-- 当前在第一页的时候不显示上一页和首页 --> <a href="http://localhost:808/php/0910/index.php?p=1">首页</a> <a href="http://localhost:808/php/0910/index.php?p=<?php echo $page-1?>">上一页</a> <?php }?> <?php for($i=1;$i<=$num;$i++){?> <a href="http://localhost:808/php/0910/index.php?p=<?php echo $i;?>" <?php echo $page==$i?'style="background-color:green;color:#fff;"':''?> ><?php echo $i;?></a> <?php }?> <?php if($page<$num){?> <!-- 当前在最后一页的时候不显示下一页和末页 --> <a href="http://localhost:808/php/0910/index.php?p=<?php echo $page+1?>">下一页</a> <a href="http://localhost:808/php/0910/index.php?p=<?php echo $num?>">末页</a> <?php }?> <!-- 实现页面的跳转 --> <form action="" method="get"> <select name="p"> <?php for($i=1;$i<=$num;$i++){?> <option value="<?php echo $i;?>" <?php if($page == $i) echo 'selected';?>><?php echo $i;?></option> <?php }?> </select> <button>跳转</button> </form> </h2> </body> </html>
点击 "运行实例" 按钮查看在线实例