FormData验证用户登录
连接数据库对用户登录信息验证
- 连接数据库文件connect.php
- 前端登录文件login.html
- 后端处理文件login.php
- 数据表mysql->user表
用户输入登录信息后查询数据库中是否存在用户信息,有提示登录成功。没有提示用户名密码错误。
- connect.php 源码:
<?php
// 连接数据库
// PDO连接对象
$pdo = new PDO('mysql:host=localhost;dbname=mysqli', 'root', '142536');
// 设置结果默认获取方式: 关联数组
$pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
- login.html 源码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>用户登录</title>
</head>
<body>
<p>请登录:</p>
<form
action=""
method="POST"
style="display: grid; gap: 15px;"
onsubmit="return false"
>
<input
type="text"
name="username"
placeholder="用户名"
required
autofocus
/>
<input type="password" name="password" placeholder="******" required />
<button>提交</button>
</form>
<script>
var form = document.querySelector('form');
var but = document.querySelector('form button');
but.onclick = function(){
//1.创建请求对象
var xhr = new XMLHttpRequest();
//2.监听事件
xhr.onreadystatechange = function()
{
if(xhr.readyState ===4 && xhr.status ===200)
{
console.log(xhr.responseText);
var obj = JSON.parse(xhr.responseText);
var span = document.createElement('span');
span.innerHTML = obj['message'];
console.log(obj);
if(obj['status']==false)
{
span.style.color = 'red';
}
else
{
span.style.color = 'green';
}
form.appendChild(span);
}
}
//3.初始化请求参数
xhr.open("POST","login.php");
//4.使用FormData来组织数据
var data = new FormData(form);
//5.发送请求
xhr.send(data);
}
</script>
</body>
</html>
- login.php 源码:
<?php
require 'connect.php';
$sql="SELECT * FROM `user` WHERE `username`=? AND `password`=?";
$stmt = $pdo->prepare($sql);
$username = $_POST['username'];
$password = sha1($_POST['password']);
$stmt->execute([$username,$password]);
$user=$stmt->fetch();
$status = 0 ; $message = '邮箱密码错误!';
if($stmt->rowCount()>1)
{
$status = 1 ;
$message = '登录成功';
}
echo json_encode(['status'=>$status,'message'=>$message]);
- 数据表
示例图: