<?php //分页函数 if(!function_exists('fx_page')){ function fx_page($db,$table,$page,$num){ $offset = ($page -1) * 5;//得到当前页面的数据库中的位置 $sql = "SELECT * FROM {$table} LIMIT {$offset}, 5;";//准备sql语句查询staff表,5个每页 echo $sql.'<br>';//检查sql语句 $res = mysqli_query($db, $sql);//查询数据库中的staff表并保存 $rows = mysqli_fetch_all($res,MYSQLI_ASSOC);//保存关联数组 //echo '<pre>'.print_r($rows,true).'</pre>'; list($total) = mysqli_fetch_row($num); $pages = ceil ($total / 5);//得到总页数,向上取整 echo $pages;//检查当前页面数 return ['rows'=>$rows,'pages'=>$pages];//返回数据 } } ?>
<!DOCTYPE html> <html> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-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,.active{ background-color: red; color: white; } form { display: inline; } </style> </head> <body> <?php require 'fx_page.php';//引入封装页面 $db = mysqli_connect('127.0.0.1', 'root', 'root','php');//连接诶数据库 $page = isset($_GET['p']) ? $_GET['p'] : 1;//获取当前页数 $table = 'staff';//获取表明 $num = mysqli_query($db, "SELECT COUNT(*) FROM staff");//计算总页数 $data = fx_page($db,$table,$page,$num);//获取函数中的返回值 $rows = $data['rows']; $pages = $data['pages']; ?> <table> <caption> <h2>员工数据表</h2> </caption> <tr> <th>ID</th> <th>姓名</th> <th>性别</th> <th>年龄</th> <th>工资</th> </tr> <?php foreach ($rows as $row): ?> <tr> <td><?php echo $row['staff_id']; ?></td> <td><?php echo $row['name']; ?></td> <td><?php echo $row['age']; ?></td> <td><?php echo $row['sex']; ?></td> <td><?php echo $row['salary']; ?></td> </tr> <?php endforeach; ?> </table> <h3> <?php if($page !=1): ?> <a href="http://www.abc.com/phpzww/427/text5.php?p=1">首页</a> <a href="http://www.abc.com/phpzww/427/text5.php?p=<?php echo (($page-1)==0)? 1 : ($page-1);?>">上一页</a> <?php endif;?> <?php for($i=1;$i<=$pages;$i++){ echo '<a '; if($page==$i){ echo ' href="http://www.abc.com/phpzww/427/text5.php?p='.$i.'">'.$i.'</a>'; }else{ echo 'href="http://www.abc.com/phpzww/427/text5.php?p='.$i.'">'.$i.'</a>'; } } ?> <?php if($page !=$pages): ?> <a href="http://www.abc.com/phpzww/427/text5.php?p=<?php echo (($page+1)>$pages)? $pages : ($page+1);?>">下一页</a> <a href="http://www.abc.com/phpzww/427/text5.php?p=<?php echo $pages?>">尾页</a> <?php endif;?> <form action="" method="get"> 第 <select name="p" id=""> <?php for($i=1; $i<=$pages; $i++): ?> <option value="<?php echo $i; ?>" <?php if($_GET['p']==$i){echo 'selected';} ?>><?php echo $i; ?></option> <?php endfor; ?> </select> 页 <button>跳转</button> </form> </h3> </body> </html>
上一页下一页无法简化,$page需要随页面改变,正确的$page传到下面就会+-1变的不正确,如果矫正简化部分代码那么active也要随之改变反而起不到简化的作用,并且逻辑显得十分混乱