欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

更新上一个员工管理系统并为其加上登录验证功能

程序员文章站 2022-03-06 13:57:42
...

一.向staffs表中添加password字段和密码格式为 md5 字段 id 的数据用来测试

  1. alter table staffs add password varchar(128) not null after name;
  2. update staffs set password = md5(id);

二.创建一个前端页面 staffxg.html

staffxg.html样式代码:

  1. <!DOCTYPE html>
  2. <html lang="zh-CN">
  3. <head>
  4. <meta charset="UTF-8" />
  5. <meta http-equiv="X-UA-Compatible" content="IE=edge" />
  6. <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  7. <title>员工管理系统</title>
  8. <!-- 导入公共css样式代码 -->
  9. <link rel="stylesheet" href="style.css" />
  10. <style>
  11. body {
  12. margin: 0;
  13. }
  14. header {
  15. display: flex;
  16. width: 90%;
  17. justify-content: space-between;
  18. background-color: rgb(85, 11, 128);
  19. padding: 0.5em 1em;
  20. }
  21. header a {
  22. color: violet;
  23. text-decoration: none;
  24. }
  25. header a:hover {
  26. color: rgb(255, 255, 255);
  27. }
  28. header nav {
  29. margin-left: auto;
  30. }
  31. </style>
  32. </head>
  33. <body>
  34. <header>
  35. <a href="">首页</a>
  36. <!-- 登录注册渲染区域 -->
  37. <nav></nav>
  38. </header>
  39. <table>
  40. <caption>
  41. 员工管理系统
  42. </caption>
  43. <!-- 表头渲染区域 -->
  44. <thead></thead>
  45. <!-- 数据渲染区域 -->
  46. <tbody></tbody>
  47. </table>
  48. <!-- 分页渲染区域 -->
  49. <p></p>
  50. <!-- 模态框编辑区域 -->
  51. <div class="modal edit">
  52. <div class="modal-drop"></div>
  53. <div class="modal-body">
  54. <button class="close">关闭</button>
  55. <form name="editform">
  56. <table>
  57. <caption>
  58. 员工信息编辑
  59. </caption>
  60. <tbody>
  61. <tr>
  62. <td>姓名</td>
  63. <td><input type="text" value="" name="name" /></td>
  64. </tr>
  65. <tr>
  66. <td>性别</td>
  67. <td>
  68. <select name="gender">
  69. <option value="male" selected></option>
  70. <option value="female"></option>
  71. </select>
  72. </td>
  73. </tr>
  74. <tr>
  75. <td>工资</td>
  76. <td><input type="text" value="" name="salary" /></td>
  77. </tr>
  78. <tr>
  79. <td>邮箱</td>
  80. <td><input type="text" value="" name="email" /></td>
  81. </tr>
  82. <tr>
  83. <td>生日</td>
  84. <td><input type="text" value="" name="birthday" /></td>
  85. </tr>
  86. <tr>
  87. <td colspan="2"><button class="save">保存</button></td>
  88. </tr>
  89. </tbody>
  90. </table>
  91. </form>
  92. </div>
  93. </div>
  94. <!-- 模态登录区域 -->
  95. <div class="modal login">
  96. <div class="modal-drop"></div>
  97. <div class="modal-body">
  98. <button class="close">关闭</button>
  99. <form name="loginform">
  100. <table>
  101. <caption>
  102. 用户登录
  103. </caption>
  104. <tbody>
  105. <tr>
  106. <td>邮箱或账号</td>
  107. <td><input type="text" value="" name="email" placeholder="只支持数字英文或特殊字符" /></td>
  108. </tr>
  109. <tr>
  110. <td>密码</td>
  111. <td><input type="password" name="password" placeholder="*******" /></td>
  112. </tr>
  113. <tr>
  114. <td colspan="2">
  115. <button type="button" class="login">登录</button>
  116. <p class="tips"></p>
  117. </td>
  118. </tr>
  119. </tbody>
  120. </table>
  121. </form>
  122. </div>
  123. </div>
  124. <!-- 模态注册区域 -->
  125. <div class="modal register">
  126. <div class="modal-drop"></div>
  127. <div class="modal-body">
  128. <button class="close">关闭</button>
  129. <form name="registerform">
  130. <table>
  131. <caption>
  132. 用户注册
  133. </caption>
  134. <tbody>
  135. <tr>
  136. <td>姓名</td>
  137. <td><input type="text" value="" name="name" placeholder="某某某" /></td>
  138. </tr>
  139. <tr>
  140. <td>性别</td>
  141. <td>
  142. <select name="gender">
  143. <option value="male" selected></option>
  144. <option value="female"></option>
  145. </select>
  146. </td>
  147. </tr>
  148. <tr>
  149. <td>工资</td>
  150. <td><input type="text" value="" name="salary" placeholder="54551" /></td>
  151. </tr>
  152. <tr>
  153. <td>邮箱</td>
  154. <td><input type="text" value="" name="email" placeholder="21545@php.cn" /></td>
  155. </tr>
  156. <tr>
  157. <td>生日</td>
  158. <td><input type="text" value="" name="birthday" placeholder="1999-12-3" /></td>
  159. </tr>
  160. <tr>
  161. <td>密码</td>
  162. <td><input type="password" name="password" placeholder="不得少于六位数" /></td>
  163. </tr>
  164. <tr>
  165. <td>重复密码</td>
  166. <td><input type="password" name="password2" placeholder="再次输入密码" /></td>
  167. </tr>
  168. <tr>
  169. <td colspan="2">
  170. <button type="button" class="register">注册</button>
  171. <p class="tips"></p>
  172. </td>
  173. </tr>
  174. </tbody>
  175. </table>
  176. </form>
  177. </div>
  178. </div>
  179. <!-- 模态框样式 -->
  180. <style>
  181. /* 模态框初始化隐藏 */
  182. .modal {
  183. display: none;
  184. }
  185. /* 遮盖层 */
  186. .modal .modal-drop {
  187. position: fixed;
  188. background-color: rgb(0, 0, 0, 0.5);
  189. top: 0;
  190. left: 0;
  191. right: 0;
  192. bottom: 0;
  193. }
  194. .modal .modal-body {
  195. position: fixed;
  196. background-color: #fff;
  197. padding: 1em;
  198. overflow: hidden;
  199. max-width: 25em;
  200. max-height: 20em;
  201. /* 水平垂直自动居中 */
  202. top: 0;
  203. left: 0;
  204. right: 0;
  205. bottom: 0;
  206. margin: auto;
  207. }
  208. /* 登录框高度 */
  209. .modal.login .modal-body {
  210. max-height: 14em;
  211. }
  212. /* 注册框高度 */
  213. .modal.register .modal-body {
  214. max-height: 24em;
  215. }
  216. /* 关闭按钮 */
  217. .modal .modal-body .close {
  218. position: absolute;
  219. top: 1.1em;
  220. right: 1.5em;
  221. width: 3em;
  222. height: 1.5em;
  223. }
  224. </style>
  225. <!-- 导入外部js文件 -->
  226. <script src="staffxg.js"></script>
  227. </body>
  228. </html>

三.使用公共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. }

四.外部staffxg.js文件的样式代码:

  1. // 页面载入完成时默认渲染第一页数据
  2. window.onload = function () {
  3. select(1);
  4. };
  5. // 编辑和删除记录
  6. document.querySelector("table:first-of-type tbody").addEventListener("click", (ev) => {
  7. // 禁止自动点击
  8. ev.preventDefault();
  9. // 获取记录 id
  10. const id = ev.target.parentNode.parentNode.querySelector("td").textContent * 1;
  11. // 事件类型
  12. switch (ev.target.getAttribute("class")) {
  13. // 编辑
  14. case "edit":
  15. // 显示模态框
  16. document.querySelector(".modal.edit").style.display = "block";
  17. // 关闭模态框
  18. document.querySelector(".modal.edit .close").addEventListener("click", (eve) => {
  19. eve.preventDefault();
  20. document.querySelector(".modal.edit").style.display = "none";
  21. });
  22. // 保存时关闭
  23. document.querySelector(".modal.edit .save").addEventListener("click", (eve) => {
  24. eve.preventDefault();
  25. document.querySelector(".modal.edit").style.display = "none";
  26. });
  27. // 模态框外点击关闭
  28. document.querySelector(".modal.edit .modal-drop").addEventListener("click", (eve) => {
  29. eve.preventDefault();
  30. document.querySelector(".modal.edit").style.display = "none";
  31. });
  32. // 获取数据
  33. let name = ev.target.parentNode.parentNode.querySelector("td:nth-of-type(2)").textContent;
  34. let gender = ev.target.parentNode.parentNode.querySelector("td:nth-of-type(3)").textContent;
  35. let salary = ev.target.parentNode.parentNode.querySelector("td:nth-of-type(4)").textContent * 1;
  36. let email = ev.target.parentNode.parentNode.querySelector("td:nth-of-type(5)").textContent;
  37. let birthday = ev.target.parentNode.parentNode.querySelector("td:nth-of-type(6)").textContent;
  38. // console.log(id, name, gender, salary, email, birthday);
  39. // 渲染到模态框
  40. let form = document.forms.editform;
  41. form.name.value = name;
  42. form.gender.value = gender;
  43. form.salary.value = salary;
  44. form.email.value = email;
  45. form.birthday.value = birthday;
  46. // 编辑事件
  47. document.querySelector(".modal .save").addEventListener("click", (eve) => {
  48. // 禁止默认提交和冒泡
  49. eve.preventDefault();
  50. eve.stopPropagation();
  51. // 获取模态框编辑数据
  52. name = form.name.value;
  53. gender = form.gender.value;
  54. salary = form.salary.value;
  55. email = form.email.value;
  56. birthday = form.birthday.value;
  57. // console.log(id, name, gender, salary, email, birthday);
  58. // 创建对象
  59. let xhr = new XMLHttpRequest();
  60. // 配置参数
  61. xhr.open("post", "staffxg.php?action=update&id=" + id);
  62. // 处理请求
  63. xhr.onload = () => {
  64. // console.log(xhr.response);
  65. // 更新数据写回页面
  66. ev.target.parentNode.parentNode.querySelector("td:nth-of-type(2)").textContent = name;
  67. ev.target.parentNode.parentNode.querySelector("td:nth-of-type(3)").textContent = gender;
  68. ev.target.parentNode.parentNode.querySelector("td:nth-of-type(4)").textContent = salary;
  69. ev.target.parentNode.parentNode.querySelector("td:nth-of-type(5)").textContent = email;
  70. ev.target.parentNode.parentNode.querySelector("td:nth-of-type(6)").textContent = birthday;
  71. };
  72. // 发送请求
  73. xhr.send(new FormData(document.forms.namedItem("editform")));
  74. });
  75. break;
  76. // 删除
  77. case "delete":
  78. if (confirm("确认删除编号 " + id + " 记录?")) {
  79. // 创建对象
  80. let xhr = new XMLHttpRequest();
  81. // 配置参数
  82. xhr.open("get", "staffxg.php?action=delete&id=" + id);
  83. // 处理请求
  84. xhr.onload = () => {
  85. // 删除节点
  86. ev.target.parentNode.parentNode.remove();
  87. };
  88. // 发送请求
  89. xhr.send(null);
  90. }
  91. break;
  92. }
  93. });
  94. // 查
  95. function select(page = 1) {
  96. // 创建对象
  97. const xhr = new XMLHttpRequest();
  98. // 配置参数
  99. xhr.open("get", "staffxg.php?action=select&page=" + page);
  100. // 数据类型
  101. xhr.responseType = "json";
  102. // 处理请求
  103. xhr.onload = () => {
  104. // console.log(xhr.response);
  105. let pages = xhr.response.pages;
  106. let staffs = xhr.response.staffs;
  107. // 是否登录
  108. let is_login = xhr.response.is_login;
  109. // 是否管理员 admin
  110. let is_admin = xhr.response.is_admin;
  111. // 渲染表头
  112. document.querySelector("table:first-of-type thead").innerHTML = get_thead(is_admin);
  113. // 渲染数据
  114. document.querySelector("table:first-of-type tbody").innerHTML = get_datas(staffs, is_admin);
  115. // 渲染分页
  116. document.querySelector("p:first-of-type").innerHTML = get_pages(page, pages);
  117. // 渲染登录注册区
  118. show_loginout();
  119. };
  120. // 发送请求
  121. xhr.send(null);
  122. }
  123. // 无刷新分页
  124. document.querySelector("p:first-of-type").addEventListener("click", (ev) => {
  125. // 禁用默认跳转
  126. ev.preventDefault();
  127. // 点击当前激活页,无效点击
  128. if (ev.target.classList.contains("active")) return;
  129. // 去掉原激活样式
  130. [...ev.currentTarget.children].forEach((ele) => ele.classList.remove("active"));
  131. // 当前页添加激活样式
  132. ev.target.classList.add("active");
  133. // 获取当前页
  134. let page = get_current_page();
  135. // 渲染点击页的数据
  136. select(page);
  137. });
  138. // 渲染数据
  139. function get_datas(datas, is_admin = 0) {
  140. let str = "";
  141. for (let i = 0; i < datas.length; i++) {
  142. str += "<tr>";
  143. str += "<td>" + datas[i]["id"] + "</td>";
  144. str += "<td>" + datas[i]["name"] + "</td>";
  145. str += "<td>" + datas[i]["gender"] + "</td>";
  146. str += "<td>" + datas[i]["salary"] + "</td>";
  147. str += "<td>" + datas[i]["email"] + "</td>";
  148. str += "<td>" + datas[i]["birthday"] + "</td>";
  149. str += "<td>" + datas[i]["create_at"] + "</td>";
  150. // 如果登录显示编辑删除
  151. if (is_admin) {
  152. str += '<td><button class="edit">编辑</button><button class="delete">删除</button></td>';
  153. }
  154. str += "</tr>";
  155. }
  156. return str;
  157. }
  158. // 表头渲染
  159. function get_thead(is_admin = 0) {
  160. let str = "";
  161. str += "<tr>";
  162. str += "<td>编号</td>";
  163. str += "<td>姓名</td>";
  164. str += "<td>性别</td>";
  165. str += "<td>工资</td>";
  166. str += "<td>邮箱</td>";
  167. str += "<td>生日</td>";
  168. str += "<td>入职时间</td>";
  169. // 如果登录显示操作
  170. if (is_admin) {
  171. str += "<td>操作</td>";
  172. }
  173. str += "</tr>";
  174. return str;
  175. }
  176. // 分页数据
  177. function get_pages(page = 1, pages) {
  178. let paginate = "";
  179. let active = "";
  180. // 首页|上一页
  181. if (page <= 1) page = 1;
  182. if (page !== 1) {
  183. paginate += '<a href="' + document.URL + '?p=1">首页</a>';
  184. paginate += '<a href="' + document.URL + "?p=" + Math.max(1, page - 1) + '">上一页</a>';
  185. }
  186. // 高亮分页
  187. for (i = 1; i <= pages; i++) {
  188. active = "";
  189. if (page == i) active = ' class="active"';
  190. paginate += '<a href="' + document.URL + "?p=" + i + '"' + active + ">" + i + "</a>";
  191. }
  192. // 下一页|尾页
  193. if (page >= pages) page = pages;
  194. if (page !== pages) {
  195. paginate += '<a href="' + document.URL + "?p=" + Math.min(page + 1, pages) + '">下一页</a>';
  196. paginate += '<a href="' + document.URL + "?p=" + pages + '">尾页</a>';
  197. }
  198. return paginate;
  199. }
  200. // 登录|注册模态框
  201. document.querySelector("header > nav").addEventListener("click", (ev) => {
  202. // 禁止自动点击
  203. ev.preventDefault();
  204. // 事件类型
  205. switch (ev.target.getAttribute("class")) {
  206. // 登录
  207. case "login":
  208. // 显示模态框
  209. document.querySelector(".modal.login").style.display = "block";
  210. // 关闭模态框
  211. document.querySelector(".modal.login .close").addEventListener("click", (eve) => {
  212. eve.preventDefault();
  213. document.querySelector(".modal.login").style.display = "none";
  214. });
  215. // 模态框外点击关闭
  216. document.querySelector(".modal.login .modal-drop").addEventListener("click", (eve) => {
  217. eve.preventDefault();
  218. document.querySelector(".modal.login").style.display = "none";
  219. });
  220. // 登录事件
  221. document.querySelector(".modal.login .login").addEventListener("click", (eve) => {
  222. // 获取登录框数据
  223. let form = document.forms.loginform;
  224. [form.email, form.password].forEach((item) => (item.oninput = () => (tips.innerHTML = null)));
  225. // 提示框
  226. let tips = document.querySelector(".modal.login .tips");
  227. // 非空验证
  228. if (!form.email.value.trim().length) {
  229. form.email.focus();
  230. tips.innerHTML = "邮箱为空";
  231. return;
  232. }
  233. if (!form.password.value.trim().length) {
  234. form.password.focus();
  235. tips.innerHTML = "密码为空";
  236. return;
  237. }
  238. // 创建对象
  239. const xhr = new XMLHttpRequest();
  240. // 配置参数
  241. xhr.open("post", "staffxg.php?action=login");
  242. // 响应类型
  243. xhr.responseType = "json";
  244. // 处理请求
  245. xhr.onload = () => {
  246. // console.log(xhr.response);
  247. // 显示登录消息
  248. tips.innerHTML = xhr.response.msg;
  249. // 登录失败时
  250. if (xhr.response.status) {
  251. return;
  252. }
  253. // 登录成功,延时关闭登录框
  254. setTimeout(() => (document.querySelector(".modal.login").style.display = "none"), 2000);
  255. // 获取当前页码
  256. let page = get_current_page();
  257. // 渲染数据
  258. select(page);
  259. };
  260. // 发送请求
  261. xhr.send(new FormData(form));
  262. });
  263. break;
  264. // 添加和注册一样
  265. case "add":
  266. break;
  267. // 注册
  268. case "register":
  269. // 显示模态框
  270. document.querySelector(".modal.register").style.display = "block";
  271. // 关闭模态框
  272. document.querySelector(".modal.register .close").addEventListener("click", (eve) => {
  273. eve.preventDefault();
  274. document.querySelector(".modal.register").style.display = "none";
  275. });
  276. // 模态框外点击关闭
  277. document.querySelector(".modal.register .modal-drop").addEventListener("click", (eve) => {
  278. eve.preventDefault();
  279. document.querySelector(".modal.register").style.display = "none";
  280. });
  281. // 注册事件
  282. document.querySelector(".modal.register .register").addEventListener("click", (eve) => {
  283. // 获取登录框数据
  284. let form = document.forms.registerform;
  285. [form.email, form.password, form.password2].forEach((item) => (item.oninput = () => (tips.innerHTML = null)));
  286. // 提示框
  287. let tips = document.querySelector(".modal.register .tips");
  288. // 非空验证
  289. if (!form.email.value.trim().length) {
  290. form.email.focus();
  291. tips.innerHTML = "邮箱为空";
  292. return;
  293. }
  294. if (!form.password.value.trim().length) {
  295. form.password.focus();
  296. tips.innerHTML = "密码为空";
  297. return;
  298. }
  299. if (!form.password2.value.trim().length) {
  300. form.password2.focus();
  301. tips.innerHTML = "重复密码为空";
  302. return;
  303. }
  304. if (form.password.value !== form.password2.value) {
  305. form.password.focus();
  306. tips.innerHTML = "两次密码不一致";
  307. return;
  308. }
  309. // 创建对象
  310. const xhr = new XMLHttpRequest();
  311. // 配置参数
  312. xhr.open("post", "staffxg.php?action=register");
  313. // 响应类型
  314. xhr.responseType = "json";
  315. // 处理请求
  316. xhr.onload = () => {
  317. // console.log(xhr.response);
  318. // 显示注册消息
  319. tips.innerHTML = xhr.response.msg;
  320. // 注册失败时
  321. if (xhr.response.status) {
  322. return;
  323. }
  324. // 注册成功,延时关闭注册框
  325. setTimeout(() => (document.querySelector(".modal.register").style.display = "none"), 2000);
  326. // 获取当前页码
  327. let page = get_current_page();
  328. // 渲染数据
  329. select(page);
  330. };
  331. //失败回调
  332. xhr.onerror = () => console.log("XHR Fail....");
  333. // 发送请求
  334. const data = new FormData(form);
  335. data.delete("password2");
  336. xhr.send(data);
  337. });
  338. break;
  339. // 登出
  340. case "logout":
  341. // 创建对象
  342. const xhr = new XMLHttpRequest();
  343. // 配置参数
  344. xhr.open("post", "staffxg.php?action=logout");
  345. // 响应类型
  346. xhr.responseType = "json";
  347. // 处理请求
  348. xhr.onload = () => {
  349. alert("登出成功!");
  350. // 获取当前页码
  351. let page = get_current_page();
  352. // 渲染数据
  353. select(page);
  354. };
  355. // 发送请求
  356. xhr.send(null);
  357. break;
  358. //添加记录
  359. case "add":
  360. break;
  361. }
  362. });
  363. // 计算当前页码
  364. function get_current_page() {
  365. let page = 1;
  366. let select = document.querySelector("p:first-of-type").children;
  367. if (select) {
  368. let url = [...select].filter((ele) => ele.classList.contains("active")).shift().href;
  369. if (url.indexOf("?") !== -1) {
  370. page = url.split("=")[1];
  371. }
  372. }
  373. return page;
  374. }
  375. // 渲染登录注册
  376. function show_loginout() {
  377. // 创建对象
  378. const xhr = new XMLHttpRequest();
  379. // 配置参数
  380. xhr.open("get", "staffxg.php?action=loginout");
  381. // 处理请求
  382. xhr.onload = () => {
  383. // 渲染登录注册区块
  384. document.querySelector("header>nav").innerHTML = xhr.response;
  385. };
  386. // 发送请求
  387. xhr.send(null);
  388. }

五.加上staffxg.php文件

  1. <?php
  2. $config = [
  3. 'type' => 'mysql',
  4. 'host' => '127.0.0.1',
  5. 'dbname' => 'phpedu',
  6. 'port' => '3306',
  7. 'charset' => 'utf8mb4',
  8. 'username' => 'root',
  9. 'password' => 'root',
  10. ];
  11. extract($config);
  12. $dsn = sprintf('%s:host=%s;dbname=%s;port=%s;charset=%s', $type, $host, $dbname, $port, $charset);
  13. try {
  14. $pdo = new PDO($dsn, $username, $password);
  15. // 设置结果集的返回类型
  16. $pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
  17. // var_dump($pdo,'连接成功');
  18. } catch (PDOException $e) {
  19. die('连接失败:' . $e->getMessage());
  20. }
  21. // 会话开启
  22. if (!session_id()) session_start();
  23. // 每页显示记录数
  24. $action = $_GET['action'] ?? 'select';
  25. $page = $_GET['page'] ?? 1;
  26. switch ($action) {
  27. // 删
  28. case 'delete':
  29. die(del_data($pdo, $_GET['id'] ?? 0));
  30. break;
  31. // 改
  32. case 'update':
  33. $id = $_GET['id'] ?? 0;
  34. $name = $_POST['name'];
  35. $gender = $_POST['gender'];
  36. $salary = $_POST['salary'];
  37. $email = $_POST['email'];
  38. $birthday = $_POST['birthday'];
  39. die(update_data($pdo, $id, $name, $gender, $salary, $email, $birthday));
  40. break;
  41. // 查
  42. case 'select':
  43. die(get_datas($pdo, $page));
  44. // 渲染登录注册
  45. case 'loginout':
  46. if (isset($_SESSION['email']) && $_SESSION['email']) {
  47. $btn = '';
  48. // 管理权限,仅 admin 允许添加员工
  49. if (is_admin($pdo)) {
  50. $btn = ' <a href="javascript:;" class="add">添加</a>';
  51. }
  52. die('<a href="#">' . $_SESSION['email'] . '</a> &nbsp;<a href="javascript:;" class="logout">退出</a>' . $btn);
  53. } else {
  54. die('<a href="javascript:;" class="login">登录</a>&nbsp;<a href="javascript:;" class="register">注册</a>');
  55. }
  56. break;
  57. // 登录
  58. case 'login':
  59. if (isset($_SESSION['email']) && $_SESSION['email']) {
  60. die(json_encode(['status' => 1, 'Toast' => '您已经登录!']));
  61. }
  62. $sql = "SELECT email FROM staffs WHERE email = :email AND password = md5(:password)";
  63. $stmt = $pdo->prepare($sql);
  64. if ($stmt->execute($_POST)) {
  65. if ($stmt->fetch()) {
  66. // 保存 session
  67. $_SESSION['email'] = $_POST['email'];
  68. die(json_encode(['status' => 0, 'Toast' => $_POST['email'] . '登录成功,正在跳转...']));
  69. } else {
  70. die(json_encode(['status' => 1, 'Toast' => '邮箱或密码错误!']));
  71. }
  72. }
  73. die(json_encode(['status' => 1, 'Toast' => '错误报告,请刷新!']));
  74. break;
  75. // 增,和注册一样
  76. case 'add':
  77. break;
  78. // 注册
  79. case 'register':
  80. if (isset($_SESSION['email']) && $_SESSION['email']) {
  81. die(json_encode(['status' => 1, 'Toast' => '该用户已登录!']));
  82. }
  83. $sql = "SELECT COUNT(1) as count FROM staffs WHERE email = '{$_POST['email']}'";
  84. if ($pdo->query($sql)->fetch()['count']) {
  85. die(json_encode(['status' => 1, 'Toast' => '该邮箱已被注册,请重新输入!']));
  86. }
  87. $sql = 'INSERT staffs SET name = :name, password = md5(:password), gender = :gender, salary = :salary, email = :email, birthday = :birthday';
  88. $stmt = $pdo->prepare($sql);
  89. if ($stmt->execute($_POST)) {
  90. if ($stmt->rowCount()) {
  91. // 实现注册并自动登录
  92. $_SESSION['email'] = $_POST['email'];
  93. die(json_encode(['status' => 0, 'Toast' => '注册成功,正在加载...']));
  94. } else {
  95. die(json_encode(['status' => 1, 'Toast' => '注册失败,请联系管理员....']));
  96. }
  97. }
  98. die(json_encode(['status' => 1, 'Toast' => '错误报告,请刷新重试!']));
  99. break;
  100. // 登出
  101. case 'logout':
  102. if (isset($_SESSION['email'])) unset($_SESSION['email']);
  103. break;
  104. default:
  105. exit('Error!');
  106. }
  107. // 更新记录
  108. function update_data($pdo, $id, $name, $gender, $salary, $email, $birthday)
  109. {
  110. if ($id) {
  111. $sql = "UPDATE staffs SET name = :name, gender = :gender, salary = :salary, email = :email, birthday = :birthday WHERE id = :id";
  112. $stmt = $pdo->prepare($sql);
  113. $stmt->bindParam(':id', $id, PDO::PARAM_INT);
  114. $stmt->bindParam(':name', $name);
  115. $stmt->bindParam(':gender', $gender);
  116. $stmt->bindParam(':salary', $salary);
  117. $stmt->bindParam(':email', $email);
  118. $stmt->bindParam(':birthday', $birthday);
  119. $stmt->execute();
  120. if ($stmt->rowCount() > 0) {
  121. return '更新成功!';
  122. }
  123. }
  124. return '更新失败!';
  125. }
  126. // 删除记录
  127. function del_data($pdo, $id = 0)
  128. {
  129. if ($id) {
  130. $sql = "DELETE FROM staffs WHERE id = :id";
  131. $stmt = $pdo->prepare($sql);
  132. $stmt->bindParam(':id', $id, PDO::PARAM_INT);
  133. $stmt->execute();
  134. if ($stmt->rowCount() > 0) {
  135. return '删除成功!';
  136. }
  137. }
  138. return '删除出错!';
  139. }
  140. // 数据总页数
  141. function get_pages($pdo, $page = 1, $num = 5)
  142. {
  143. // 总页数
  144. $num = 5;
  145. $sql = "SELECT CEIL(COUNT(1)/{$num}) total FROM staffs";
  146. $pages = $pdo->query($sql)->fetch()['total'];
  147. return $pages;
  148. }
  149. // 每页显示数
  150. function get_datas($pdo, $page = 1, $num = 5)
  151. {
  152. // 获取总页数
  153. $pages = get_pages($pdo);
  154. // 每页显示的数据
  155. $offset = ($page - 1) * $num;
  156. $sql = "SELECT * FROM `staffs` LIMIT {$offset}, {$num}";
  157. $stmt = $pdo->prepare($sql);
  158. $stmt->execute();
  159. $staffs = $stmt->fetchAll();
  160. // $staffs = $pdo->query($sql)->fetchAll();
  161. return json_encode(['pages' => $pages, 'staffs' => $staffs, 'is_admin' => is_admin($pdo)]);
  162. }
  163. // 是否为管理员 admin
  164. function is_admin($pdo)
  165. {
  166. if (isset($_SESSION['email']) && $_SESSION['email']) {
  167. $sql = "SELECT COUNT(1) as count FROM staffs WHERE email = '{$_SESSION['email']}' AND name = 'admin'";
  168. if ($pdo->query($sql)->fetch()['count']) {
  169. return true;
  170. }
  171. }
  172. return false;
  173. }

效果预览:

更新上一个员工管理系统并为其加上登录验证功能

注册一个hoay 用户名称效果预览:

更新上一个员工管理系统并为其加上登录验证功能

注册成功并自动登录效果预览:

更新上一个员工管理系统并为其加上登录验证功能

单击退出当前用户效果预览:

更新上一个员工管理系统并为其加上登录验证功能更新上一个员工管理系统并为其加上登录验证功能

登录管理员admin用户效果预览:

更新上一个员工管理系统并为其加上登录验证功能

登录成功:

更新上一个员工管理系统并为其加上登录验证功能

对hoay用户进行删除效果预览:

更新上一个员工管理系统并为其加上登录验证功能

删除成功:

更新上一个员工管理系统并为其加上登录验证功能