Correcting teacher:查无此人
Correction status:qualified
Teacher's comments:完成的不错,继续加油。
一、SESSION 登录实战
connect.php
<?php # connect.php文件 // 数据库连接参数 $db = [ 'type' => 'mysql', 'host' => 'localhost', 'dbname' => 'movie', 'username' => 'root', 'password' => 'root', 'port' => 3306 ]; $dsn = "{$db['type']}:host={$db['host']};dbname={$db['dbname']}"; // 连接数据库 try { $pdo = new PDO($dsn, $db['username'], $db['password']); } catch (PDOException $e) { die('错误信息: ' . $e->getMessage()); }
<?php //开启会话 session_start(); // 1: 已登录: 显示出用户的登录信息, 显示退出按钮 if (isset($_SESSION['username']) ) { echo '用户: ' . $_SESSION['username'] . '已登录<br>'; echo '<a href="dispatch.php?action=logout">退出</a>'; } else { // 2. 未登录,就跳转到登录页面 echo '<a href="dispatch.php?action=login">请登录</a>'; }
<?php // 开启会话 session_start(); // 连接数据库 require 'connect.php'; // 获取请求参数 $action = isset($_GET['action']) ? $_GET['action'] : 'login'; $action = htmlentities(strtolower(trim($action))); switch ($action) { case 'login': include __DIR__ . '/login.php'; break; case 'check': include __DIR__ . '/check.php'; break; case 'logout': include __DIR__ . '/logout.php'; break; default: include __DIR__ . '/index.php'; }
<?php if (isset($_SESSION['username'])) { echo '<script>alert("不要重复登录");location.assign("index.php");</script>'; } ?> <!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <title>用户登录</title> </head> <body> <h3>用户登录</h3> <form action="dispatch.php?action=check" method="post"> <p> <label for="username">用户名:</label> <input type="username" name="username" id="username"> </p> <p> <label for="password">密码:</label> <input type="password" name="password" id="password"> </p> <p> <button>提交</button> </p> </form> </body> </html>
<?php if ($_SERVER['REQUEST_METHOD'] === 'POST'){ if (empty($_POST['username'])) { echo '<script>alert("用户名不能为空");history.back();</script>'; } elseif (empty($_POST['password'])) { echo '<script>alert("密码不能为空");history.back();</script>'; } else { $username = $_POST['username']; $password = md5($_POST['password']); $sql = 'SELECT * FROM `users` WHERE `username` = :username AND `password` = :password LIMIT 1'; $stmt = $pdo->prepare($sql); $stmt->execute(['username'=>$username,'password'=>$password]); $user = $stmt->fetch(PDO::FETCH_ASSOC); if (empty($user)) { echo '<script>alert("登录失败,请检查用户名或密码是否正确");history.back();</script>'; } else { $_SESSION['username'] = $user['username']; echo '<script>alert("登录成功");location.assign("index.php");</script>'; } } } else { die('请求类型错误'); }
<?php if (isset($_SESSION['username'])) { session_destroy(); echo '<script>alert("退出成功");location.assign("index.php");</script>'; } else { // 要求用户先登录 echo '<script>alert("请先登录");location.assign("login.php");</script>'; }
二、练熟pdo操作,增删查改(手写)