html+php+mysql的注册登录写个代码,html需要表单验证 和数据库创建代码
时间: 2023-06-27 07:08:06 浏览: 101
HTML+PHP+数据库实现注册登录
HTML 表单:
```
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>注册/登录</title>
</head>
<body>
<h1>用户注册</h1>
<form action="register.php" method="post">
<p>用户名:<input type="text" name="username" required>(必填)</p>
<p>密码:<input type="password" name="password" required>(必填)</p>
<p>确认密码:<input type="password" name="confirm_password" required>(必填)</p>
<p>邮箱:<input type="email" name="email" required>(必填)</p>
<p><input type="submit" value="注册"></p>
</form>
<h1>用户登录</h1>
<form action="login.php" method="post">
<p>用户名:<input type="text" name="username" required>(必填)</p>
<p>密码:<input type="password" name="password" required>(必填)</p>
<p><input type="submit" value="登录"></p>
</form>
</body>
</html>
```
PHP 注册:
```
<?php
// 连接数据库
$conn = mysqli_connect('localhost', 'root', 'password', 'test');
if (!$conn) {
die("连接数据库失败:" . mysqli_connect_error());
}
// 获取表单数据
$username = $_POST['username'];
$password = $_POST['password'];
$email = $_POST['email'];
// 验证密码
if ($_POST['password'] != $_POST['confirm_password']) {
die("两次输入的密码不一致");
}
// 查询用户名是否已存在
$sql = "SELECT * FROM users WHERE username='$username'";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
die("用户名已存在");
}
// 插入用户数据
$sql = "INSERT INTO users (username, password, email) VALUES ('$username', '$password', '$email')";
if (mysqli_query($conn, $sql)) {
echo "注册成功";
} else {
echo "注册失败:" . mysqli_error($conn);
}
// 关闭数据库连接
mysqli_close($conn);
?>
```
PHP 登录:
```
<?php
// 连接数据库
$conn = mysqli_connect('localhost', 'root', 'password', 'test');
if (!$conn) {
die("连接数据库失败:" . mysqli_connect_error());
}
// 获取表单数据
$username = $_POST['username'];
$password = $_POST['password'];
// 查询用户是否存在
$sql = "SELECT * FROM users WHERE username='$username' AND password='$password'";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
echo "登录成功";
} else {
echo "用户名或密码错误";
}
// 关闭数据库连接
mysqli_close($conn);
?>
```
MySQL 数据库创建:
```
CREATE DATABASE test;
USE test;
CREATE TABLE users (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
username VARCHAR(30) NOT NULL,
password VARCHAR(30) NOT NULL,
email VARCHAR(50) NOT NULL
);
```
阅读全文