Blogger Information
Blog 41
fans 0
comment 0
visits 41300
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
静态单页|项目数据|无刷新分页|编辑与删除功能
幸福敲门的博客
Original
1232 people have browsed it
  1. 将项目改造成无刷新分页,前端用Ajax实现数据异步加载
  2. 实现记录的编辑与删除功能,想一下如何优雅的实现它

一、 数据库建表

  1. create table staffs (
  2. sid int unsigned auto_increment not null primary key,
  3. name varchar(20) not null comment '姓名',
  4. gender enum('male','female') not null comment '性别',
  5. email varchar(150) not null comment '邮箱',
  6. birthday date not null comment '生日',
  7. create_at timestamp not null default current_timestamp comment '创建日期',
  8. update_at timestamp not null default current_timestamp on update current_timestamp comment '更新日期'
  9. ) engine = innodb auto_increment=1 collate = utf8mb4_unicode_ci;

二、插入数据

  1. -- 插入 insert
  2. insert staffs (name,gender,salary,email,birthday)
  3. values ('Lee','male',4500,'lee@php.cn','1983-02-10');
  4. insert staffs set name='King', gender='male',salary=8899,
  5. email='king@qq.com', birthday='1988-09-23';
  6. insert staffs (name,gender, salary, email,birthday) values
  7. ('king','male',6500,'king@php.cn','1992-10-29'),
  8. ('amy','female',7800,'amy@163.com','1998-10-22'),
  9. ('betty','female',9800,'betty@qq.com','1953-10-19'),
  10. ('jack','male',12500,'jack@php.cn', '1977-10-24'),
  11. ('marry','female',15800,'marry@php.cn', '1990-01-08'),
  12. ('alice','female',8600,'alice@php.cn','1989-09-18'),
  13. ('admin','male',16600,'admin@php.cn','1989-09-18'),
  14. ('lisa','female',13500,'lisa@qq.com','1983-09-13'),
  15. ('peter','male',9600,'peter@163.com','1993-09-29'),
  16. ('linda','female',5600,'linda@163.com','1993-09-29');

图示:
数据库插入数据

三、因为要使用到数据库,首先需要做的是数据库配置:
3.1 config.php 数据库配置文件

  1. <?php
  2. // 数据库的配置参数
  3. return [
  4. 'type' => 'mysql',
  5. 'host' => '127.0.0.1',
  6. 'dbname' => 'phpedu',
  7. 'port' => '3306',
  8. 'charset' => 'utf8mb4',
  9. 'username' => 'root',
  10. 'password' => 'root',
  11. ];

数据库配置完毕之后,连接数据库,创建PDO对象。

3.2 connect.php 连接数据库文件

  1. <?php
  2. // 连接数据库
  3. // dsn: 数据源名称
  4. // dsn: 数据库的驱动类型,默认数据库,端口号,字符集
  5. // $dsn = 'mysql:host=127.0.0.1;dbname=phpedu;port=3306;charset=utf8mb4';
  6. // $username = 'root';
  7. // $password = 'root';
  8. // 导入配置文件
  9. $config = require __DIR__ . '/config.php';
  10. // 将关联数组成员解析成独立变量
  11. extract($config);
  12. // $dsn = sprintf('%s:host=%s;dbname=%s;port=%s;charset=%s',$type,$host,$dbname,$port,$charset);
  13. // $dsn = sprintf('%s:host=%s;dbname=%s;',$type,$host,$dbname);
  14. $dsn = sprintf('%s:dbname=%s;',$type,$dbname);
  15. try {
  16. $pdo =new PDO($dsn, $username, $password);
  17. // $pdo =new PDO('mysql:dbname=phpedu','root','root');
  18. // 设置结果集的返回类型
  19. $pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
  20. // var_dump($pdo,'连接成功');
  21. } catch (PDOException $e) {
  22. die( '连接失败:' . $e->getMessage());
  23. }

3.3 以上工作完成之后,写index.php页面,这是最开始的入口页面:

  1. <?php require 'sql.php' ?>
  2. <!doctype html>
  3. <html lang="en">
  4. <head>
  5. <meta charset="UTF-8">
  6. <meta name="viewport"
  7. content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
  8. <meta http-equiv="X-UA-Compatible" content="ie=edge">
  9. <title>员工管理系统2021初版</title>
  10. <link rel="stylesheet" href="style.css">
  11. </head>
  12. <body>
  13. <table>
  14. <caption><h2>员工管理系统2021初版</h2></caption>
  15. <thead>
  16. <tr>
  17. <td>编号</td>
  18. <td>姓名</td>
  19. <td>年龄</td>
  20. <td>性别</td>
  21. <td>工资</td>
  22. <td>邮箱</td>
  23. <td>生日</td>
  24. <td>入职时间</td>
  25. <td>操作</td>
  26. </tr>
  27. </thead>
  28. <tbody>
  29. <?php foreach ($staffs as $staff) : ?>
  30. <tr>
  31. <td><?= $staff['sid'] ?></td>
  32. <td><?= $staff['name'] ?></td>
  33. <td><?= $staff['age'] ?></td>
  34. <td><?= $staff['gender']=='male' ? '男':'女' ?></td>
  35. <td><?= $staff['salary'] ?></td>
  36. <td><?= $staff['email'] ?></td>
  37. <td><?= $staff['birthday'] ?></td>
  38. <td><?= $staff['create_at'] ?></td>
  39. <td>
  40. <button onclick="location.href='edit.php?action=edit&sid=<?=$staff['sid']?>'">编辑</button>
  41. <button onclick="del(<?=$staff['sid']?>)">删除</button>
  42. </td>
  43. </tr>
  44. <?php endforeach ?>
  45. </tbody>
  46. </table>
  47. <p>
  48. <!-- 实现上一页和首页 -->
  49. <!-- 处理上一页和首页的变量和逻辑-->
  50. <?php $prev = $page==1? 1:$page-1; ?>
  51. <!-- 显示实现上一页和首页,按钮 -->
  52. <?php if($page !=1): ?>
  53. <a href="<?=$_SERVER['PHP_SELF'].'?p=1' ?>">首页</a>
  54. <a href="<?=$_SERVER['PHP_SELF'].'?p='. $prev ?>">上一页</a>
  55. <?php endif ?>
  56. <!-- 显示每一页按钮 -->
  57. <?php for ($i=1; $i<=$pageNum; $i++) : ?>
  58. <?php
  59. $jump = sprintf('%s?p=%d', $_SERVER['PHP_SELF'], $i);
  60. $active = ($i == $page) ? 'active':'';
  61. ?>
  62. <a href="<?=$jump ?>" class="<?=$active ?>"><?= $i ?></a>
  63. <?php endfor ?>
  64. <!-- 实现下一页和尾页 -->
  65. <!-- 处理下一页和尾页的变量和逻辑-->
  66. <?php $prev = $page==$pageNum? $pageNum:$page+1; ?>
  67. <!-- 显示实现上一页和首页,按钮 -->
  68. <?php if($page !=$pageNum): ?>
  69. <a href="<?=$_SERVER['PHP_SELF'].'?p='. $prev ?>">下一页</a>
  70. <a href="<?=$_SERVER['PHP_SELF'].'?p='. $pageNum?>">尾页</a>
  71. <?php endif ?>
  72. </p>
  73. </body>
  74. <script>
  75. function del(sid) {
  76. let url = 'handle.php?action=del&id=' + sid;
  77. return confirm('是否删除编号为: '+sid+' 的员工数据?') ? location.href=url : false;
  78. }
  79. </script>
  80. </html>

3.3-1 style.css样式:

  1. * {
  2. margin: 0;
  3. padding: 0;
  4. box-sizing: border-box;
  5. color: #555;
  6. }
  7. body {
  8. display: flex;
  9. flex-direction: column;
  10. align-items: center;
  11. }
  12. /*表格样式*/
  13. table {
  14. width: 90%;
  15. border: 1px solid;
  16. border-collapse: collapse;
  17. text-align: center;
  18. }
  19. table caption {
  20. font-size: 1.2rem;
  21. margin: 10px;
  22. }
  23. table td,
  24. table th {
  25. border: 1px solid;
  26. padding: 5px;
  27. }
  28. table tr:hover {
  29. background-color: #eee;
  30. }
  31. table thead tr:only-of-type {
  32. background-color: lightcyan;
  33. }
  34. table button {
  35. width: 56px;
  36. height: 26px;
  37. }
  38. table button:last-of-type {
  39. color: red;
  40. }
  41. table button {
  42. cursor: pointer;
  43. margin: 0 3px;
  44. }
  45. /*分页条样式*/
  46. body > p {
  47. display: flex;
  48. }
  49. p > a {
  50. text-decoration: none;
  51. color: #555;
  52. border: 1px solid #888;
  53. padding: 5px 10px;
  54. margin: 10px 2px;
  55. }
  56. .active {
  57. background-color: seagreen;
  58. color: white;
  59. border: 1px solid seagreen;
  60. }

3.4 sql.php数据库链接页面

  1. <?php
  2. require __DIR__ . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'connect.php';
  3. //每页条目数
  4. $num = 10;
  5. // 当前的页码通常是能过GET请求过来的
  6. $page = $_GET['p'] ?? 1;
  7. // 计算当前页的起始偏移量
  8. $offset = ($page - 1) * $num;
  9. //获取分页后总条目数, 使用别名total后,变量$pageNum的结果: Array( [ceil(count(*)/10)] => 8 )
  10. $sql = "select ceil(count(*)/{$num}) total from `staffs`;";
  11. $stmt = $pdo->prepare($sql);
  12. $stmt->execute();
  13. $pageNum = $stmt->fetch()['total'];
  14. //echo $pageNum;
  15. // 2. 每页要显示的数据?
  16. $sql = "select * from `staffs` limit {$offset}, {$num};";
  17. $stmt = $pdo->prepare($sql);
  18. $stmt->execute();
  19. $staffs = $stmt->fetchAll();

3.5 handle.php

  1. <?php
  2. //连接数据库, 拿到PDO对象
  3. require __DIR__ . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'connect.php';
  4. //获取操作参数
  5. $action = $_GET['action'];
  6. $sid = $_GET['sid'];
  7. //print_r(array_values($_POST));
  8. //die();
  9. //执行操作,数据库的,查找、修改、删除
  10. switch ($action) {
  11. case 'edit':
  12. header('location:edit.php?sid='.$sid);
  13. break;
  14. case 'update':
  15. $sql = <<< sql
  16. update staffs set
  17. name=?,age=?,gender=?,salary=?,email=?,birthday=?
  18. where sid={$sid};
  19. sql;
  20. //// 教程中的代码
  21. // $stmt = $pdo->prepare($sql);
  22. // $stmt->execute(array_values($_POST));
  23. // 简写代码, 直接返回执行结果, 受影响的条目数量
  24. $res = $pdo->prepare($sql)->execute(array_values($_POST));
  25. // sql语句测试打印代码
  26. // echo $stmt->debugDumpParams();
  27. if ($res) {
  28. echo '<script>alert("更新成功");location.href="index.php";</script>';
  29. }
  30. break;
  31. case 'del':
  32. $sql = 'delete from `staffs` where `sid` = ?;';
  33. $stmt = $pdo->prepare($sql);
  34. $stmt->execute([$sid]);
  35. if ($stmt->rowCount() == 1) {
  36. echo '<script>alert("删除成功");location.href="index.php";</script>';
  37. }
  38. break;
  39. default:
  40. return ('非法操作...');
  41. }

3.6 edit.php修改删除页面

  1. <?php
  2. //连接数据库, 拿到PDO对象
  3. require __DIR__ . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'connect.php';
  4. $sid = $_GET['sid'];
  5. $sql = 'select * from `staffs` where sid= ?';
  6. $stmt = $pdo->prepare($sql);
  7. $stmt->execute([$sid]);
  8. $staff = $stmt->fetch();
  9. //print_r($staff);
  10. ?>
  11. <!doctype html>
  12. <html lang="en">
  13. <head>
  14. <meta charset="UTF-8">
  15. <meta name="viewport"
  16. content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
  17. <meta http-equiv="X-UA-Compatible" content="ie=edge">
  18. <title>修改员工信息</title>
  19. </head>
  20. <body>
  21. <form action="handle.php?action=update&sid=<?=$sid?>" method="post">
  22. <div class="box" >
  23. <div>修改员工信息</div>
  24. <div>
  25. <span>编号:</span>
  26. <input type="text" value="<?=$staff['sid'] ?>" disabled>
  27. </div>
  28. <div>
  29. <span>姓名:</span>
  30. <input type="text" name="name" value="<?=$staff['name'] ?>">
  31. </div>
  32. <div>
  33. <span>年龄:</span>
  34. <input type="text" name="age" value="<?=$staff['age'] ?>">
  35. </div>
  36. <div>
  37. <span>性别:</span>
  38. <input type="text" name="gender" value="<?=$staff['gender'] ?>">
  39. </div>
  40. <div>
  41. <span>工资:</span>
  42. <input type="text" name="salary" value="<?=$staff['salary'] ?>">
  43. </div>
  44. <div>
  45. <span>邮箱:</span>
  46. <input type="text" name="email" value="<?=$staff['email'] ?>">
  47. </div>
  48. <div>
  49. <span>生日:</span>
  50. <input type="text" name="birthday" value="<?=$staff['birthday'] ?>">
  51. </div>
  52. <div>
  53. <span>入职时间:</span>
  54. <input type="text" value="<?=$staff['create_at'] ?>" disabled>
  55. </div>
  56. <div>
  57. <button type="submit">保存</button>
  58. </div>
  59. </div>
  60. </form>
  61. </body>
  62. </html>

3.7 AJAX无刷新分页按提交作业的同学去写,编号那块显示不正常,自己还没有找到解决办法,这两天在想办法解决一下
AJAX无刷新分页 编号显示不对

index.php图示:
index.php首页

修改信息:
![修改lee为张大彪]
修改lee为张大彪

修改后显示张大飙图示:
修改后显示张大飙

点击第二页后首页显示出来

点击第二页后首页显示出来

Correcting teacher:天蓬老师天蓬老师

Correction status:qualified

Teacher's comments:
Statement of this Website
The copyright of this blog article belongs to the blogger. Please specify the address when reprinting! If there is any infringement or violation of the law, please contact admin@php.cn Report processing!
All comments Speak rationally on civilized internet, please comply with News Comment Service Agreement
0 comments
Author's latest blog post