html+php+mysql的注册登录写个代码,需要表单验证 和数据库创建代码
时间: 2023-06-27 20:08:03 浏览: 123
以下是一个简单的注册登录系统的HTML+PHP+MySQL代码:
HTML代码(register.html):
```
<!DOCTYPE html>
<html>
<head>
<title>注册页面</title>
</head>
<body>
<h1>注册页面</h1>
<form method="post" action="register.php">
<label>用户名:</label>
<input type="text" name="username" required><br><br>
<label>密码:</label>
<input type="password" name="password" required><br><br>
<label>确认密码:</label>
<input type="password" name="confirm_password" required><br><br>
<input type="submit" value="注册">
</form>
</body>
</html>
```
HTML代码(login.html):
```
<!DOCTYPE html>
<html>
<head>
<title>登录页面</title>
</head>
<body>
<h1>登录页面</h1>
<form method="post" action="login.php">
<label>用户名:</label>
<input type="text" name="username" required><br><br>
<label>密码:</label>
<input type="password" name="password" required><br><br>
<input type="submit" value="登录">
</form>
</body>
</html>
```
PHP代码(register.php):
```
<?php
// 数据库连接信息
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "testdb";
// 获取表单提交的数据
$username = $_POST['username'];
$password = $_POST['password'];
$confirm_password = $_POST['confirm_password'];
// 表单验证
if ($password != $confirm_password) {
echo "两次输入的密码不一致,请重新输入!";
exit;
}
// 创建数据库连接
$conn = new mysqli($servername, $username, $password, $dbname);
// 检查连接是否成功
if ($conn->connect_error) {
die("连接失败: " . $conn->connect_error);
}
// SQL查询语句
$sql = "INSERT INTO users (username, password) VALUES ('$username', '$password')";
// 执行SQL查询
if ($conn->query($sql) === TRUE) {
echo "注册成功!";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
// 关闭数据库连接
$conn->close();
?>
```
PHP代码(login.php):
```
<?php
// 数据库连接信息
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "testdb";
// 获取表单提交的数据
$username = $_POST['username'];
$password = $_POST['password'];
// 创建数据库连接
$conn = new mysqli($servername, $username, $password, $dbname);
// 检查连接是否成功
if ($conn->connect_error) {
die("连接失败: " . $conn->connect_error);
}
// SQL查询语句
$sql = "SELECT * FROM users WHERE username='$username' AND password='$password'";
// 执行SQL查询
$result = $conn->query($sql);
// 检查查询结果是否为空
if ($result->num_rows > 0) {
echo "登录成功!";
} else {
echo "用户名或密码错误!";
}
// 关闭数据库连接
$conn->close();
?>
```
MySQL代码(创建数据库和表):
```
CREATE DATABASE testdb;
USE testdb;
CREATE TABLE users (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
username VARCHAR(30) NOT NULL,
password VARCHAR(30) NOT NULL
);
```
以上代码仅供参考,具体实现方式可能因环境和需求不同而有所不同。
阅读全文