封装函数代码:
实例
<?php function connect($servername, $username, $password,$dbName){ //连接mysql $link=@mysqli_connect($servername, $username, $password,$dbName); if (!$link) { die("Connection failed: " . mysqli_connect_error()); } return $link; } function check($link,$table,$num){ $page = isset($_GET['p']) ? $_GET['p'] : 1; $offset = ($page-1)*$num; $sql = "SELECT * FROM {$table} LIMIT {$offset}, {$num};"; $res = mysqli_query($link,$sql); $rows = mysqli_fetch_all($res,MYSQLI_ASSOC); // echo '<pre>'; // print_r($rows); // echo'</pre>'; // if (!$rows) { // printf("Error: %s\n", mysqli_error($link)); // exit(); // } //获取总页数分2步:1.获取总记录数,2.再除以每次的显示数量,结果向上取整 $number = mysqli_query($link,"SELECT COUNT(*) FROM {$table}"); list($total) = mysqli_fetch_row($number); //总记录数保存到变量$total中 $pages = ceil($total / $num); //获取到总页数 $pages $word=[$page,$rows,$pages]; return $word; }
运行实例 »
点击 "运行实例" 按钮查看在线实例
前台页面代码:
实例
<!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"> <title>品牌电脑报价表</title> <style> table,th,td { border: 1px solid black; } table th { background-color: lightskyblue; } table { border-collapse: collapse; width: 70%; margin: 30px auto; text-align: center; } h3 { text-align: center; } h3 a { text-decoration: none; margin-left: 10px; border: 1px solid black; display: inline-block; height: 30px; min-width: 30px; padding: 0 10px; background-color: lightgreen; } h3 a:hover{ background-color: red; color: white; } </style> </head> <body> <?php require 'func.php'; $servername='127.0.0.1'; $username='root'; $password='root'; $charset='utf8'; $dbName='shop'; $link=connect($servername, $username, $password,$dbName); $table='s_shop'; $num=5; $word=check($link,$table,$num); $pages=$word[2]; $page=$word[0]; ?> <table> <caption><h2>牌电脑报价表</h2></caption> <tr> <th>序号</th> <th>品牌</th> <th>型号</th> <th>产地</th> <th>价格</th> </tr> <?php foreach ($word[1] as $row): ?> <tr> <td><?php echo $row['id']; ?></td> <td><?php echo $row['name']; ?></td> <td><?php echo $row['spec']; ?></td> <td><?php echo $row['place']; ?></td> <td><?php echo $row['price']; ?></td> </tr> <?php endforeach;?> </table> <h3> <!-- 当前是第一页的时候,上一页和首页链接应该不显示--> <?php if($page != 1): ?> <a href="check.php?p=1">首页</a> <a href="check.php?p= <?php // echo $page-1;//发现到第一页就挂掉了,怎么办?必须对$page=0进行控制 echo (($page-1)==0)? 1 : ($page-1); ?>">上一页</a> <?php endif; ?> <!--生成中间页码--> <?php for($i=1; $i<=$pages; $i++): ?> <a href="check.php?p=<?php echo $i ?>"><?php echo $i ?></a> <?php endfor; ?> <!--当前已经是最后一页的时候,下一页和最后一页也应该不显示--> <?php if($page != $pages) :?> <a href="check.php?p= <?php //发现越界了,怎么办?最大页不能超过总页数才可以. echo (($page+1)>$pages)?$pages:($page+1); ?>">下一页</a> <a href="check.php?p=<?php echo $pages; ?>">尾页</a> <?php endif; ?> </h3> </body> </html>
运行实例 »
点击 "运行实例" 按钮查看在线实例
总结:原理都清楚,但是手生,下来常练吧!