实例
<?php /** * Created by PhpStorm. * User: Administrator * Date: 2018/5/6 0006 * Time: 11:17 */ if (!function_exists('func_page')) { function func_page($db, $table, $page = 1, $num = 5) { $offset = ($page - 1) * $num; $sql = "SELECT * FROM {$table} LIMIT {$offset}, {$num};"; $res = mysqli_query($db, $sql); $rows = mysqli_fetch_all($res, MYSQLI_ASSOC); $number = mysqli_query($db, "SELECT COUNT(*) FROM {$table}"); list($total) = mysqli_fetch_row($number); $pages = ceil($total / $num); return ['rows' => $rows, 'pages' => $pages]; } }
运行实例 »
点击 "运行实例" 按钮查看在线实例
实例
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>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 'lib/fun.php'; $db = mysqli_connect('localhost','root','root','php'); $page = isset($_GET['p']) ? $_GET['p'] : 1; $num = 4; $table = 'user'; $data = func_page($db,$table,$page,$num); $rows = $data['rows']; //当前分页数据 $pages = $data['pages']; //总页数 $page = ($page == 0) ? 1 : $page; $page = ($page > $pages) ? $pages : $page; ?> <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['id']; ?></td> <td><?php echo $row['name']; ?></td> <td><?php echo $row['age']; ?></td> <td><?php echo $row['sex']; ?></td> <td><?php echo $row['money']; ?></td> </tr> <?php endforeach; ?> </table> <h3> <?php if($page != 1): ?> <a href="http://localhost/demo1/0427/demo.php?p=1">首页</a> <a href="http://localhost/demo1/0427/demo.php?p=<?php echo $page-1; ?>">上一页</a> <?php endif; ?> <?php for ($i = 1; $i <= $pages; $i++): ?> <a class="<?php if($_GET['p']==$i){echo 'active';}?>" href="http://localhost/demo1/0427/demo.php?p=<?php echo $i ?>"><?php echo $i ?></a> <?php endfor; ?> <?php if($page != $pages) :?> <a href="http://localhost/demo1/0427/demo.php?p=<?php echo $page+1; ?>">下一页</a> <a href="http://localhost/demo1/0427/demo.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>
运行实例 »
点击 "运行实例" 按钮查看在线实例