Blogger Information
Blog 43
fans 0
comment 0
visits 30476
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
动态分页与composer演泽
橙絮圆
Original
595 people have browsed it

动态分页与composer演泽

作业标题:0825作业
作业内容:请实例演绎以下作业: 1.做一个做动态分页? 2.composer自动加载机制你了解多少? 3.请使用composer安装三方验证码库完善你的登录页面?


  1. 做一个做动态分页?
    index1.php显示程序代码
  1. <?require 'pageData.php'?>
  2. <!DOCTYPE html>
  3. <html lang="en"></html>
  4. <head>
  5. <meta charset="UTF-8">
  6. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  7. <title>数据显示</title>
  8. <link rel="stylesheet" href="style.css">
  9. </head>
  10. <body>
  11. <table>
  12. <caption>用户信息表</caption>
  13. <thead>
  14. <tr>
  15. <td>编号</td>
  16. <td>姓名</td>
  17. <td>性别</td>
  18. <td>创建时间</td>
  19. <td>操作</td>
  20. </tr>
  21. </thead>
  22. <tbody>
  23. <?php foreach($users as $user):?>
  24. <tr>
  25. <td><?= $user['id']?></td>
  26. <td><?= $user['uname']?></td>
  27. <td><?= $user['gender']==1?'男':'女'?></td>
  28. <td><?= date("Y-m-d H:m:s",$user['create_time'])?></td>
  29. <td><button>删除</button><button>编辑</button></td>
  30. </tr>
  31. <?php endforeach;?>
  32. </tbody>
  33. </table>
  34. <!-- 动态分页 -->
  35. <!-- 生成动态分页条 -->
  36. <p>
  37. <?php $pre=$page-1;if($page!=1):?>
  38. <a href="?p=1">首页</a>
  39. <a href="?p=<?=$pre?>">上一页</a>
  40. <?endif?>
  41. <?php for ($i=1; $i <= $pages; $i++) :
  42. $active='active' ;
  43. // 生成一个动态的a href 属性的值
  44. $jump = sprintf('?p=%d',$i);
  45. $active = ($i==$page)?'active':null;
  46. ?>
  47. <a class="<?=$active?>" href="<?=$jump?>"><?=$i?></a>
  48. <?endfor?>
  49. <?php $next=$page+1;if($page!=$pages):?>
  50. <a href="?p=<?=$next?>">下一页</a>
  51. <a href="?p=<?=$pages?>">尾页</a>
  52. <?endif?>
  53. </p>
  54. </body>
  55. </html>

PageData.php数据库连接代码以及分页相关计算逻辑

  1. <?php
  2. $pdo = new PDO('mysql:host=localhost;dbname=16','root','root',[PDO::ATTR_ERRMODE=> PDO::ERRMODE_WARNING,PDO::ATTR_DEFAULT_FETCH_MODE=>PDO::FETCH_ASSOC]);
  3. //获取分页数据 :每页显示的数量 默认为3
  4. $num =3;
  5. //当前页码,默认为1
  6. $page = $_GET['p'] ?? 1;
  7. //计算每一页第一条记录的显示偏移量
  8. //偏移量 = (页码 -1) \* 每页的显示数量
  9. $offset = ($page - 1) * $num ;
  10. //获取分页数据
  11. $sql = " SELECT `id`,`uname`,`gender`,`create_time` FROM `user` ORDER BY `id` ASC LIMIT {$num} OFFSET {$offset} ";
  12. //$sql = "SELECT * FROM `user` LIMIT {$offset},{$num } ";
  13. $users = $pdo->query($sql)->fetchAll();
  14. // print_r($users);
  15. //获取总页数
  16. // $sql = "SELECT CEIL(COUNT(`id`)/{$num}) AS `sum` FROM `user`";
  17. $sql = "SELECT COUNT(`id`) AS `sum` FROM `user`";
  18. $count = $pdo->query($sql)->fetch()['sum'];
  19. $pages = ceil($count/$num);
  20. // var_dump($pages);

示例演示图
分页


2.composer自动加载机制你了解多少?

  1. <?php
  2. // 1.
  3. // spl_autoload_register(function($className){
  4. // require $className .'.php';
  5. // });
  6. // 2. composer 类的自动加载机制
  7. /**
  8. * 1. 在项目的compose.json文件中添加autoload字段 files 可以加载任意位置的类文件
  9. * "files": [
  10. "app/controller/Login.php",
  11. "app/controller/User.php",
  12. "app/controller/Auth.php"
  13. ]
  14. 修改完成以后,每添加一个新的类文件,要追加绑定并且必须要执行composer dump-autoload命令才能生效
  15. */
  16. /**
  17. * 2. 在项目的compose.json文件中添加autoload字段 classmap 类映射 实现类的批量注册
  18. "classmap": [
  19. "app/controller"
  20. ]
  21. 修改完成以后,必须要执行composer dump-autoload命令才能生效
  22. */
  23. /**
  24. * 3. psr-4规范 :类的命名空间与类文件所在的目录进行绑定,并且类文件名称与类名称保持一致
  25. * 命名空间最后必须以“\”空间分隔符结束,这样以来在绑定的目录中添加新的类时 不必执行composer dump-autoload命令就能生效
  26. */
  27. require 'vendor/autoload.php';
  28. use app\controller\User;
  29. use app\controller\Login;
  30. use app\controller\Auth;
  31. use app\controller\Article;
  32. use extend\lib\Auth as libAuth;
  33. echo User::index();
  34. echo Login::index();
  35. echo Auth::index();
  36. echo Article::index();
  37. echo libAuth::index();
  1. {
  2. "name": "phpcn/login",
  3. "description": "a perfect login page with captcha",
  4. "type": "project",
  5. "require": {
  6. "almasaeed2010/adminlte": "3.0.5",
  7. "gregwar/captcha": "1.1.7"
  8. },
  9. "authors": [
  10. {
  11. "name": "imzchloe",
  12. "email": "952637517@qq.com"
  13. }
  14. ],
  15. "autoload": {
  16. "psr-4": {
  17. "app\\controller\\": "app/controller",
  18. "extend\\lib\\": "extend/lib"
  19. }
  20. }
  21. }

3.请使用composer安装三方验证码库完善你的登录页面?
login.php前端代码

  1. <?php
  2. // We need the session to check the phrase after submitting
  3. session_start();
  4. ?>
  5. <!DOCTYPE html>
  6. <html lang="zh-CN">
  7. <head>
  8. <meta charset="UTF-8">
  9. <title>登录</title>
  10. </head>
  11. <body>
  12. <h2>用户登录</h2>
  13. <table>
  14. <tr>
  15. <td>账户</td>
  16. <td><input type="text" name="username"></td>
  17. <td><span id="err_msg"></span></td>
  18. </tr>
  19. <tr>
  20. <td>密码</td>
  21. <td><input type="password" name="password"></td>
  22. </tr>
  23. </tr>
  24. <tr>
  25. <td>请输入验证码</td>
  26. <td><input type="text" name="phrase" /></td>
  27. <td><img src="session.php" onclick="this.src=this.src+'&k='+Math.random();"/></td>
  28. </tr>
  29. <tr align="center">
  30. <td colspan="2">
  31. <input type="button" id='btn' name="btn" value="确定">
  32. </td>
  33. </tr>
  34. </table>
  35. <script type="text/javascript" src="
  36. https://cdn.bootcss.com/jquery/3.3.1/jquery.min.js"></script>
  37. <script>
  38. //const btn1=document.getElementsByName("btn");
  39. const btn1 = document.getElementById('btn');
  40. // alert(btn1);
  41. // btn1.addEventListener("click",function(){
  42. // alert("aaa");
  43. // });
  44. // btn1.addEventListener("click",function(){
  45. // alert("bbb");
  46. // });
  47. //登录
  48. btn1.addEventListener("click",function(){
  49. //alert("aaa");
  50. var data = {};
  51. data.username = $.trim($('input[name="username"]').val());
  52. data.password = $.trim($('input[name="password"]').val());
  53. data.phrase = $.trim($('input[name="phrase"]').val());
  54. data.type = 3;
  55. if(data.username == '' || data.password == '')
  56. {
  57. alert('用户名或者密码不能为空哦~');
  58. return;
  59. }
  60. $.post('3-doSubmit.php',data,function(res){
  61. console.log(res);
  62. if(res.status == 1)
  63. {
  64. alert(res.msg);
  65. top.location='5-index.php';
  66. }else{
  67. alert(res.msg);
  68. }
  69. },"json")
  70. })
  71. </script>
  72. </body>
  73. </html>

接收数据并处理3-doSubmit.php代码

  1. <?php
  2. namespace pdo_chloe;
  3. require 'common.php';
  4. // 接收数据
  5. // var_dump($_POST);
  6. $username = !empty($_POST['username']) && isset($_POST['username']) ? $_POST['username']:null;
  7. $password = !empty($_POST['password']) && isset($_POST['password']) ? md5($_POST['password']):null;
  8. $gender = !empty($_POST['gender']) && isset($_POST['gender']) ? intval($_POST['gender']):null;
  9. $phrase=(isset($_SESSION['phrase']) && $_SESSION['phrase'] === $_POST['phrase'])?$_POST['phrase']:null;
  10. $create_time = time();
  11. // //验证码
  12. // if (isset($_SESSION['phrase']) && $_SESSION['phrase'] === $_POST['phrase']) {
  13. // echo "<h1>Captcha is valid !</h1>";
  14. // } else {
  15. // echo "<h1>Captcha is not valid!</h1>";
  16. // }
  17. // // The phrase can't be used twice
  18. // unset($_SESSION['phrase']);
  19. //请求分发器 type 1 检查用户名重名 2注册 3 登录
  20. $type = isset($_POST['type'])&&!empty($_POST['type']) ? intval($_POST['type']):null;
  21. switch ($type) {
  22. case 1:
  23. $res = checkUname($username);
  24. if($res)
  25. {
  26. echo json_encode(['status'=>0,'msg'=>'用户名已被占用'],320);
  27. }else{
  28. echo json_encode(['status'=>1,'msg'=>'用户名合法'],320);
  29. }
  30. break;
  31. case 2:
  32. $flag = checkUname($username);
  33. if(!$flag){
  34. $res = insertData($username,$password,$gender,$create_time);
  35. if($res)
  36. {
  37. echo json_encode(['status'=>1,'msg'=>'注册成功'],320);
  38. exit;
  39. }
  40. echo json_encode(['status'=>0,'msg'=>'注册失败'],320);
  41. exit;
  42. }
  43. echo json_encode(['status'=>0,'msg'=>'请勿重复提交'],320);
  44. break;
  45. case 3:
  46. $res = login($username,$password);
  47. if ($res) {
  48. //echo json_encode(['status'=>1,'msg'=>'用户名密码正确'], 320);
  49. if ($phrase) {
  50. echo json_encode(['status'=>1,'msg'=>'验证成功'], 320);
  51. } else {
  52. echo json_encode(['status'=>0,'msg'=>'验证码错误'], 320);
  53. }
  54. }else{
  55. echo json_encode(['status'=>0,'msg'=>'用户名或密码错误'],320);
  56. }
  57. // if($phrase){
  58. // echo json_encode(['status'=>1,'msg'=>'验证正确'],320);exit;
  59. // }
  60. // echo json_encode(['status'=>0,'msg'=>'验证码错误'],320);
  61. break;
  62. default:
  63. # code...
  64. break;
  65. }

程序过滤验证代码common.php

  1. <?php
  2. session_start();
  3. //公共模型文件
  4. // 连接数据库
  5. require '1-connect.php';
  6. /**
  7. * 检测用户注册用户名是否被占用
  8. * param:用户名
  9. * return : 被占用返回true 未被占用返回false
  10. */
  11. function checkUname($username)
  12. {
  13. global $pdo;
  14. $isOccupied = false;//默认数据库中不存在同名用户名
  15. $sql = "SELECT `uname` FROM `user` WHERE `uname`='{$username}'";
  16. $res = $pdo->query($sql)->fetch();
  17. // 已存在同名昵称
  18. if($res)
  19. {
  20. $isOccupied = true;
  21. }
  22. return $isOccupied;
  23. }
  24. /**
  25. * param:用户注册 用户名 密码 性别 创建时间
  26. * return : 注册成功返回true 失败返回false
  27. */
  28. function insertData($username,$password,$gender,$create_time)
  29. {
  30. global $pdo;
  31. $flag = false;
  32. if( !empty($username) && !empty($password) && !empty($gender)){
  33. $sql = "INSERT INTO `user` SET `uname` = '{$username}', `pwd`='{$password}', `gender` = {$gender},`create_time`={$create_time};";
  34. $res = $pdo->exec($sql);
  35. if($res)
  36. {
  37. $flag = true;
  38. }
  39. }
  40. return $flag;
  41. }
  42. /**
  43. * param:用户登录 用户名 密码
  44. * return : 登录成功返回true 失败返回false
  45. */
  46. function login($username,$password)
  47. {
  48. global $pdo;
  49. $flag = false;
  50. if(!empty($username) && !empty($password))
  51. {
  52. // 可以把它看作是想要运行的 SQL 的一种编译过的模板
  53. // 使用问号参数占位符来构成预处理语句
  54. $sql = "SELECT `uname`,`pwd` FROM `user` WHERE `uname`= ? AND `pwd`= ?";
  55. // $sql = "SELECT `uname`,`pwd` FROM `user` WHERE `id`> 0 ";
  56. // echo $sql;
  57. // PDO::prepare — 准备要执行的语句,并返回语句对象
  58. $stmt = $pdo->prepare($sql);
  59. // 绑定一个PHP变量到用作预处理的SQL语句中的对应问号占位符,此变量作为引用被绑定,并只在 PDOStatement::execute() 被调用的时候才取其值。
  60. // $stmt->bindParam(1,$username,PDO::PARAM_STR);
  61. // $stmt->bindParam(2,$password,PDO::PARAM_STR);
  62. // 执行一条预处理语句 成功时返回 true, 或者在失败时返回 false。
  63. // $username = 'admin';
  64. $stmt->execute([$username,$password]);
  65. $res = $stmt->fetch();
  66. // var_dump($res);
  67. if($res)
  68. {
  69. $_SESSION['uname'] = $res['uname'];
  70. $flag = true;
  71. }
  72. // var_dump($stmt);//object(PDOStatement)
  73. // foreach($stmt as $v)
  74. // {
  75. // print_r($v);
  76. // }
  77. // die;
  78. }
  79. return $flag;
  80. }

数据库连接代码 1-connect.php

  1. <?php
  2. namespace connect_chloe;
  3. use PDO;
  4. $config = require __DIR__ .'\\config\\database.php';
  5. extract($config);
  6. // dsn data source name 包括pDO驱动名称 主机名 端口号 数据库名称
  7. $dsn = sprintf('%s:host=%s;port=%d;dbname=%s',$type,$host,$port,$dbname);
  8. try {
  9. $pdo = new PDO($dsn,$username,$password,[PDO::ATTR_ERRMODE=>PDO::ERRMODE_WARNING]);
  10. // var_dump($pdo);
  11. $pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE,PDO::FETCH_ASSOC);
  12. } catch (\Exception $e) {
  13. die('Connection error : ' . $e->getMessage());
  14. }

第三方验证码session.php代码

  1. <?php
  2. // We need the session to store the correct phrase for later check
  3. session_start();
  4. // Including the autoload (you need to composer install in the main directory)
  5. require_once __DIR__.'/../vendor/autoload.php';
  6. use Gregwar\Captcha\CaptchaBuilder;
  7. // Creating the captcha instance and setting the phrase in the session to store
  8. // it for check when the form is submitted
  9. $captcha = new CaptchaBuilder;
  10. $_SESSION['phrase'] = $captcha->getPhrase();
  11. // Setting the header to image jpeg because we here render an image
  12. header('Content-Type: image/jpeg');
  13. // Running the actual rendering of the captcha image
  14. $captcha
  15. ->build()
  16. ->output()
  17. ;

实例图
验证码
验证成功

Correcting teacher:PHPzPHPz

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