博客列表 >运用会话控制、PDO预处理实现记住用户和分页功能

运用会话控制、PDO预处理实现记住用户和分页功能

lilove的博客
lilove的博客原创
2020年08月26日 00:11:41848浏览

实例整体结构

  • check.php:登陆检查

  • control.php:控制台页(含分页功能)

  • db.php:数据库连接

  • index.php:主页

  • login.php:登录页

  • personal.php:个人中心页

  • rcheck.php:注册检查

  • register.php:注册页面

  • edit.php:编辑页面

  • handle.php:功能分配

代码

  • check.php:登陆检查
  1. <?php
  2. // 处理登录提交
  3. $username = $_POST['username'];
  4. $password = sha1($_POST['password']);
  5. $remember = $_POST['rem'];
  6. // 连接数据库
  7. require 'db.php';
  8. // PDO查询数据库
  9. $select = "SELECT `id`,`user_name`,`password` FROM `user` WHERE `user_name`=:username AND `password`=:pwd";
  10. $data = $pdo->prepare($select);
  11. $data->bindParam(':username', $username);
  12. $data->bindParam(':pwd', $password);
  13. $data->execute();
  14. $res = $data->fetch(PDO::FETCH_ASSOC);
  15. // 根据查询结果验证登陆数据及是否记住密码
  16. if ($data->rowCount() == 1) {
  17. // 清理已有的cookie
  18. setcookie('username', '', time() - 3600);
  19. setcookie('auth', '', time() - 3600);
  20. // 如果选择了记住密码
  21. if ($remember == 'on') {
  22. setcookie('username', $username, strtotime('+7 days'));
  23. // 加盐生成令牌
  24. $salt = '小刚';
  25. $auth = sha1($username . $password . $salt) . ',' . $res['id'];
  26. setcookie('auth', $auth, strtotime('+7 days'));
  27. } else {
  28. setcookie('username', $username);
  29. $salt = '小刚';
  30. $auth = sha1($username . $password . $salt) . ',' . $res['id'];
  31. setcookie('auth', $auth);
  32. }
  33. exit("<script>
  34. alert('登陆成功');
  35. location.href = 'index.php';
  36. </script>");
  37. } else {
  38. exit("<script>
  39. alert('登陆失败');
  40. location.href = 'login.php';
  41. </script>");
  42. }

  • control.php:控制台页(含分页功能)
  1. <?php
  2. require "db.php";
  3. $select = "SELECT `id`,`user_name`,`password`,`user_type` FROM `user`";
  4. $data = $pdo->prepare($select);
  5. $data->execute();
  6. $res = $data->fetchAll();
  7. if ($data->rowCount() == 0) {
  8. exit("<script>
  9. alert('查询失败')
  10. </script>");
  11. }
  12. // 分页
  13. // 1.每页显示数量
  14. $num = 1;
  15. // 2.当前页码,默认为1
  16. $page = $_GET['p'] ?? 1;
  17. // 3.计算每页第一条记录偏移量
  18. $offset = ($page - 1) * $num;
  19. // 4.获取分页数据
  20. $pagedata = "SELECT * FROM `user` LIMIT {$num} OFFSET {$offset}";
  21. // 语句简写
  22. // $pagedata = "SELECT * FROM `user` LIMIT {$offset}, {$num}";
  23. $users = $pdo->query($pagedata)->fetchAll();
  24. // 5.计算总页数
  25. // 计算表中共计有多少条记录,每页显示几条
  26. // 总页数=ceil(记录总数/每页的记录数):ceil()向上取整函数
  27. $sql = "SELECT CEIL(COUNT(`id`)/{$num}) AS `total` FROM `user`";
  28. $pages = $pdo->query($sql)->fetch()['total'];
  29. ?>
  30. <!DOCTYPE html>
  31. <html lang="zh-cn">
  32. <head>
  33. <meta charset="UTF-8">
  34. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  35. <link rel="stylesheet" href="layui/css/layui.css" media="all" />
  36. <title>控制台</title>
  37. </head>
  38. <style>
  39. body {
  40. min-width: 1000px;
  41. }
  42. .tab {
  43. width: 900px;
  44. margin: 0 auto;
  45. }
  46. .container {
  47. width: 500px;
  48. margin: 0 auto;
  49. }
  50. .pag {
  51. font-size: 0;
  52. margin: 10px auto;
  53. }
  54. .pag > li {
  55. display: inline-block;
  56. min-width: 30px;
  57. height: 20px;
  58. font-size: 16px;
  59. }
  60. .pag > li > a {
  61. display: block;
  62. line-height: 20px;
  63. text-align: center;
  64. padding: 5px;
  65. border: 1px solid gray;
  66. }
  67. .pag > li > a:hover {
  68. color: white;
  69. background-color: teal;
  70. }
  71. .active {
  72. color: white;
  73. background-color: teal;
  74. }
  75. </style>
  76. <body>
  77. <table class="layui-table tab">
  78. <colgroup>
  79. <col width="150">
  80. <col width="200">
  81. <col>
  82. </colgroup>
  83. <thead>
  84. <tr>
  85. <th>ID</th>
  86. <th>用户名</th>
  87. <th>密码</th>
  88. <th>用户类型</th>
  89. <th>操作</th>
  90. </tr>
  91. </thead>
  92. <tbody>
  93. <?foreach ($users as $user):?>
  94. <tr>
  95. <td><?echo $user["id"]?></td>
  96. <td><?echo $user["user_name"]?></td>
  97. <td><?echo $user["password"]?></td>
  98. <td><?echo $user["user_type"] == 1 ? "管理员" : "非管理员"?></td>
  99. <td>
  100. <button class="layui-btn layui-btn-xs" onclick="location.href='handle.php?action=edit&userid=<?=$user['id']?>'">编辑</button>
  101. <button class="layui-btn layui-btn-xs layui-btn-warm" onclick="location.href='handle.php?action=del&userid=<?=$user['id']?>'">删除</button>
  102. </td>
  103. </tr>
  104. <?endforeach?>
  105. </tbody>
  106. </table>
  107. <div class="container">
  108. <ul class="pag">
  109. <li><a href="<?=$_SERVER['PHP_SELF']. '?p=1'?>">首页</a></li>
  110. <?php
  111. // 上一页
  112. $prev = ($page-1) == 0 ? 1 : ($page-1);
  113. // 下一页
  114. $next = ($page+1) > $pages ? $pages : ($page+1);
  115. ?>
  116. <li><a href="<?=$_SERVER['PHP_SELF']. '?p='. $prev?>">上一页</a></li>
  117. <?php for ($i=1; $i<=$pages; $i++): ?>
  118. <?php
  119. // $i是分页条中的页码,$page是url中get获取到的页码
  120. $active = ($i == $page) ? 'active' : null;
  121. // $_SERVER['PHP_SELF']是全局变量中的url地址,做字符串拼接get请求参数
  122. // $jump = $_SERVER['PHP_SELF']. '?p='. $i;
  123. // 可以用sprintf()拼接url字符串
  124. $jump = sprintf("%s?p=%s", $_SERVER['PHP_SELF'], $i);
  125. ?>
  126. <li><a href="<?=$jump?>" class="<?=$active?>"><?=$i?></a></li>
  127. <?php endfor ?>
  128. <li><a href="<?=$_SERVER['PHP_SELF']. '?p='. $next?>">下一页</a></li>
  129. <li><a href="<?=$_SERVER['PHP_SELF']. '?p='. $pages?>">尾页</a></li>
  130. </ul>
  131. </div>
  132. <script src="layui/layui.js" charset="utf-8"></script>
  133. </body>
  134. </html>

  • db.php:数据库连接
  1. <?php
  2. // 配置mysql数据库连接参数
  3. define('DB_HOST', 'localhost');
  4. define('DB_PORT', 3306);
  5. define('DB_NAME', 'phptest');
  6. define('DB_USER', 'root');
  7. define('DB_PWD', '123456');
  8. define('DB_TYPE', 'mysql');
  9. define('DB_CHARSET', 'utf8');
  10. // 配置PDO连接数据库参数,DSN:datasoursename
  11. define('DB_DSN', DB_TYPE . ':host=' . DB_HOST . ';dbname=' . DB_NAME . ';charset=' . DB_CHARSET);
  12. // 捕获错误,比较消耗资源
  13. try {
  14. $pdo = new PDO(DB_DSN, DB_USER, DB_PWD);
  15. // 抛出一个 PDOException 异常
  16. } catch (PDOException $e) {
  17. echo $e->getMessage();
  18. // 捕获拥有Throwable接口的错误或者其他异常
  19. } catch (Throwable $e) {
  20. echo $e->getMessage();
  21. }
  22. // 可设置默认以索引数组方式获取结果集
  23. $pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);

  • index.php:主页
  1. <?php
  2. // 连接数据库
  3. require 'db.php';
  4. $token = $_COOKIE['auth'];
  5. $auth_true = explode(',', $token)[0];
  6. $id = end(explode(',', $token));
  7. $select = "SELECT `id`,`user_name`,`password` FROM `user` WHERE `id`=:id";
  8. $data = $pdo->prepare($select);
  9. $data->bindParam(':id', $id);
  10. $data->execute();
  11. $res = $data->fetch();
  12. if ($data->rowCount() === 1) {
  13. $username = $res['user_name'];
  14. $password = $res['password'];
  15. $salt = '小刚';
  16. $auth = sha1($username . $password . $salt);
  17. if ($auth_true !== $auth) {
  18. exit("<script>
  19. alert('未登录');
  20. location.href='login.php';
  21. </script>");
  22. }
  23. } else {
  24. exit("<script>
  25. alert('请先登录');
  26. location.href='login.php';
  27. </script>");
  28. }
  29. ?>
  30. <!DOCTYPE html>
  31. <html lang="zh-cn">
  32. <head>
  33. <meta charset="UTF-8" />
  34. <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  35. <link rel="stylesheet" href="layui/css/layui.css" media="all" />
  36. <title>主页</title>
  37. </head>
  38. <style>
  39. body {
  40. margin: 0 30px;
  41. }
  42. </style>
  43. <body>
  44. <ul class="layui-nav">
  45. <li class="layui-nav-item">
  46. <a href="control.php" target="_blank">控制台<span class="layui-badge">9</span></a>
  47. </li>
  48. <li class="layui-nav-item">
  49. <a href=<?php echo "personal.php"."?username={$username}" ?> target="_blank">个人中心<span class="layui-badge-dot"></span></a>
  50. </li>
  51. <li class="layui-nav-item layui-layout-right" lay-unselect="">
  52. <a href="javascript:;"><img src="face.jpg" class="layui-nav-img">
  53. <?php echo $_COOKIE['username']; ?>
  54. </a>
  55. <dl class="layui-nav-child">
  56. <dd><a href="javascript:;">修改信息</a></dd>
  57. <dd><a href="javascript:;">修改密码</a></dd>
  58. <dd><a href="login.php?action=logout">退出</a></dd>
  59. </dl>
  60. </li>
  61. </ul>
  62. </body>
  63. <script src="layui/layui.js" charset="utf-8"></script>
  64. <script>
  65. layui.use('element', function() {
  66. //导航的hover效果、二级菜单等功能,需要依赖element模块
  67. var element = layui.element;
  68. });
  69. </script>
  70. </html>

  • login.php:登录页
  1. <?php
  2. // 退出清cookie
  3. if ($_GET['action'] == 'logout') {
  4. setcookie('username', '', time() - 3600);
  5. setcookie('auth', '', time() - 3600);
  6. exit("<script>
  7. location.href='login.php';
  8. </script>");
  9. }
  10. // 连接数据库
  11. require 'db.php';
  12. $token = $_COOKIE['auth'];
  13. $auth_true = explode(',', $token)[0];
  14. $id = end(explode(',', $token));
  15. $select = "SELECT `id`,`user_name`,`password` FROM `user` WHERE `id`=:id";
  16. $data = $pdo->prepare($select);
  17. $data->bindParam(':id', $id);
  18. $data->execute();
  19. $res = $data->fetch();
  20. if ($data->rowCount() == 1) {
  21. $username = $res['user_name'];
  22. $password = $res['password'];
  23. $salt = '小刚';
  24. $auth = sha1($username . $password . $salt);
  25. if ($auth_true == $auth) {
  26. exit("<script>
  27. alert('已登陆');
  28. location.href='index.php';
  29. </script>");
  30. }
  31. }
  32. ?>
  33. <!DOCTYPE html>
  34. <html lang="zh-cn">
  35. <head>
  36. <meta charset="UTF-8" />
  37. <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  38. <link rel="stylesheet" href="layui/css/layui.css" />
  39. <title>登录页</title>
  40. </head>
  41. <style>
  42. .container {
  43. width: 400px;
  44. min-height: 400px;
  45. margin: 100px auto;
  46. }
  47. </style>
  48. <body>
  49. <form class="layui-form container" action="check.php" method="POST">
  50. <div class="layui-form-item">
  51. <label class="layui-form-label">用户名</label>
  52. <div class="layui-input-block">
  53. <input type="text" name="username" lay-verify="required" lay-reqtext="用户名是必填项" placeholder="请输入用户名" autocomplete="off" class="layui-input" />
  54. </div>
  55. </div>
  56. <div class="layui-form-item">
  57. <label class="layui-form-label">密码</label>
  58. <div class="layui-input-block">
  59. <input type="password" name="password" lay-verify="required" lay-reqtext="密码是必填项" placeholder="请输入密码" autocomplete="off" class="layui-input" />
  60. </div>
  61. </div>
  62. <div class="layui-form-item">
  63. <label class="layui-form-label">记住密码</label>
  64. <div class="layui-input-block">
  65. <input type="checkbox" name="rem" lay-skin="switch" lay-filter="switchTest" lay-text="开启|关闭" />
  66. </div>
  67. </div>
  68. <div class="layui-form-item">
  69. <div class="layui-input-block">
  70. <button type="submit" class="layui-btn" lay-submit="" lay-filter="login">
  71. 登陆
  72. </button>
  73. <a href="register.php" class="layui-btn layui-btn-normal" target="_blank">注册</a>
  74. </div>
  75. </div>
  76. </form>
  77. </body>
  78. <script src="layui/layui.js" charset="utf-8"></script>
  79. <script>
  80. layui.use(["form"], function() {
  81. var form = layui.form,
  82. layer = layui.layer;
  83. });
  84. </script>
  85. </html>

  • personal.php:个人中心页
  1. <?php
  2. require "db.php";
  3. $username = $_GET['username'];
  4. $select = "SELECT `id`,`user_name`,`password`,`user_type` FROM `user` WHERE `user_name`=:username";
  5. $data = $pdo->prepare($select);
  6. $data->bindParam(':username', $username);
  7. $data->execute();
  8. $res = $data->fetch();
  9. if ($data->rowCount() !== 1) {
  10. exit("<javascript>
  11. alert('用户不存在')
  12. </javascript>");
  13. }
  14. ?>
  15. <!DOCTYPE html>
  16. <html lang="zh-cn">
  17. <head>
  18. <meta charset="UTF-8" />
  19. <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  20. <link rel="stylesheet" href="layui/css/layui.css" />
  21. <title>个人中心</title>
  22. </head>
  23. <style>
  24. .container {
  25. width: 400px;
  26. min-height: 400px;
  27. margin: 100px auto;
  28. }
  29. </style>
  30. <body>
  31. <form class="layui-form container" action="javascript:void(0)" method="POST">
  32. <div class="layui-form-item">
  33. <label class="layui-form-label">ID</label>
  34. <div class="layui-input-block">
  35. <input type="text" name="userid" autocomplete="off" class="layui-input" value=<?echo $res["id"]?> disabled />
  36. </div>
  37. </div>
  38. <div class="layui-form-item">
  39. <label class="layui-form-label">用户名</label>
  40. <div class="layui-input-block">
  41. <input type="text" name="username" autocomplete="off" class="layui-input" value=<?echo $res["user_name"]?> disabled />
  42. </div>
  43. </div>
  44. <div class="layui-form-item">
  45. <label class="layui-form-label">密码</label>
  46. <div class="layui-input-block">
  47. <input type="password" name="password" autocomplete="off" class="layui-input" value=<?echo $res["password"]?> disabled />
  48. </div>
  49. </div>
  50. <div class="layui-form-item">
  51. <label class="layui-form-label">用户类型</label>
  52. <div class="layui-input-block">
  53. <input type="text" name="usertype" autocomplete="off" class="layui-input" value=<?echo $res["user_type"] == 1 ? "管理员" : "非管理员"?> disabled />
  54. </div>
  55. </div>
  56. <div class="layui-form-item">
  57. <div class="layui-input-block">
  58. <button type="submit" class="layui-btn" lay-submit="" lay-filter="login" onclick="window.close()">
  59. 关闭
  60. </button>
  61. </div>
  62. </div>
  63. </form>
  64. </body>
  65. <script src="layui/layui.js" charset="utf-8"></script>
  66. <script>
  67. layui.use(["form"], function() {
  68. var form = layui.form,
  69. layer = layui.layer;
  70. });
  71. </script>
  72. </html>

  • rcheck.php:注册检查
  1. <?php
  2. // 处理注册提交
  3. $username = $_POST['username'];
  4. $password = sha1($_POST['password']);
  5. // 连接数据库
  6. require 'db.php';
  7. // PDO查询数据库
  8. $select = "SELECT `id`,`user_name` FROM `user` WHERE `user_name`=:username";
  9. $data = $pdo->prepare($select);
  10. $data->bindParam(':username', $username);
  11. $data->execute();
  12. $res = $data->fetch();
  13. // 根据查询结果验证注册数据
  14. if ($data->rowCount() == 1) {
  15. // 如果已经存在用户
  16. exit("<script>
  17. alert('用户已存在');
  18. location.href = 'register.php';
  19. </script>");
  20. }
  21. $insert = "INSERT INTO user(`user_name`,`password`) VALUES(:username,:pwd)";
  22. $data = $pdo->prepare($insert);
  23. $data->bindParam(':username', $username);
  24. $data->bindParam(':pwd', $password);
  25. $data->execute();
  26. $res = $data->fetch();
  27. if ($data->rowCount() == 1) {
  28. // 如果插入数据成功
  29. exit("<script>
  30. alert('注册成功');
  31. location.href = 'login.php';
  32. </script>");
  33. }else {
  34. exit("<script>
  35. alert('注册失败');
  36. location.href = 'register.php';
  37. </script>");
  38. }

  • register.php:注册页面
  1. <!DOCTYPE html>
  2. <html lang="zh-cn">
  3. <head>
  4. <meta charset="UTF-8" />
  5. <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  6. <link rel="stylesheet" href="layui/css/layui.css" />
  7. <title>注册页</title>
  8. </head>
  9. <style>
  10. .container {
  11. width: 400px;
  12. min-height: 400px;
  13. margin: 100px auto;
  14. }
  15. </style>
  16. <body>
  17. <form class="layui-form container" action="rcheck.php" method="POST">
  18. <div class="layui-form-item">
  19. <label class="layui-form-label">用户名</label>
  20. <div class="layui-input-block">
  21. <input type="text" name="username" lay-verify="required" lay-reqtext="用户名是必填项" placeholder="请输入用户名" autocomplete="off" class="layui-input" />
  22. </div>
  23. </div>
  24. <div class="layui-form-item">
  25. <label class="layui-form-label">密码</label>
  26. <div class="layui-input-block">
  27. <input type="password" name="password" lay-verify="required" lay-reqtext="密码是必填项" placeholder="请输入密码" autocomplete="off" class="layui-input" />
  28. </div>
  29. </div>
  30. <div class="layui-form-item">
  31. <div class="layui-input-block">
  32. <button type="submit" class="layui-btn" lay-submit="" lay-filter="login">
  33. 提交
  34. </button>
  35. </div>
  36. </div>
  37. </form>
  38. </body>
  39. <script src="layui/layui.js" charset="utf-8"></script>
  40. <script>
  41. layui.use(["form"], function() {
  42. var form = layui.form,
  43. layer = layui.layer;
  44. });
  45. </script>
  46. </html>

  • edit.php:编辑页面
  1. <?php
  2. $edit = $pdo->query("SELECT * FROM `user` WHERE `id`={$userid}")->fetch();
  3. ?>
  4. <!DOCTYPE html>
  5. <html lang="zh-cn">
  6. <head>
  7. <meta charset="UTF-8">
  8. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  9. <link rel="stylesheet" href="layui/css/layui.css" media="all" />
  10. <title>编辑表单</title>
  11. </head>
  12. <style>
  13. .container {
  14. width: 400px;
  15. min-height: 200px;
  16. margin: 100px auto;
  17. }
  18. </style>
  19. <body>
  20. <fieldset class="layui-elem-field container">
  21. <legend>编辑用户</legend>
  22. <div class="layui-field-box">
  23. <form class="layui-form" action="<?php echo $_SERVER['PHP_SELF']. '?action=doedit&userid='. $edit['id']; ?>" method="POST">
  24. <div class="layui-form-item">
  25. <label class="layui-form-label">用户名</label>
  26. <div class="layui-input-block">
  27. <input type="text" name="username" required lay-verify="required" autocomplete="off" class="layui-input" value="<?=$edit['user_name']?>">
  28. </div>
  29. </div>
  30. <div class="layui-form-item">
  31. <label class="layui-form-label">密码</label>
  32. <div class="layui-input-block">
  33. <input type="password" name="password" required lay-verify="required" autocomplete="off" class="layui-input" placeholder="请输入新密码">
  34. </div>
  35. </div>
  36. <div class="layui-form-item">
  37. <div class="layui-input-block">
  38. <button type="submit" class="layui-btn" lay-submit="" lay-filter="formDemo">保存</button>
  39. <button type="reset" class="layui-btn layui-btn-primary">重置</button>
  40. </div>
  41. </div>
  42. </form>
  43. </div>
  44. </fieldset>
  45. </body>
  46. <script src="layui/layui.js" charset="utf-8"></script>
  47. <script>
  48. layui.use('form', function(){
  49. var form = layui.form;
  50. //监听提交
  51. // form.on('submit(formDemo)', function(data){
  52. // layer.msg(JSON.stringify(data.field));
  53. // return false;
  54. // });
  55. });
  56. </script>
  57. </html>

  • handle.php:功能分配
  1. <?php
  2. require "db.php";
  3. $action = $_GET['action'];
  4. $userid = $_GET['userid'];
  5. switch ($action) {
  6. case 'edit':
  7. // 加载、渲染数据编辑表单
  8. include 'edit.php';
  9. break;
  10. case 'doedit':
  11. $doedit = "UPDATE `user` SET `user_name`=?, `password`=? WHERE `id`=?";
  12. $stmt = $pdo->prepare($doedit);
  13. if (!empty($_POST)) {
  14. $pwd = sha1($_POST['password']);
  15. $stmt->execute([$_POST['username'], $pwd, $userid]);
  16. echo $stmt->rowCount() == 1 ? "<script>alert('修改成功!');location.href='control.php';</script>" : "<script>alert('修改失败!');location.href='control.php';</script>";
  17. }
  18. break;
  19. case 'del':
  20. $del = "DELETE FROM `user` WHERE `id`=?";
  21. $data = $pdo->prepare($del);
  22. $data->execute([$userid]);
  23. if ($data->rowCount() == 1) {
  24. exit("<script>alert('删除成功');location.href='control.php';</script>");
  25. } else {
  26. exit("<script>alert('删除失败');location.href='control.php';</script>");
  27. }
  28. break;
  29. }

功能演示

  • 记住密码登陆:

  • 退出登录再直接进入主页提示先登陆:

  • 注册后登陆:

  • 渲染数据:

  • 简单分页:
    • 上一页、下一页;
    • 首页、尾页;

  • 编辑:

  • 删除:


总结

  • 将PDO预处理操作数据库和会话控制整合到实际案例中做了个大作业,还加入了分页功能,希望老师别打我呀:)

  • 提前预习了下前端框架layui的使用,感觉很强大,但有一定局限性。

声明:本文内容转载自脚本之家,由网友自发贡献,版权归原作者所有,如您发现涉嫌抄袭侵权,请联系admin@php.cn 核实处理。
全部评论
文明上网理性发言,请遵守新闻评论服务协议