In the process of website development, user login system is a very common function. One of the important steps is to verify whether the username and password entered by the user match, ensuring that the user enters the correct information before entering the system.
This article will introduce how to use PHP and MySQL to implement user name verification function.
First, we need to create a database in MySQL and create a user table in it. In this user table, we need to include the following fields:
We can use the following SQL statement to create this user table:
CREATE DATABASE test;
USE test;
CREATE TABLE users (
id INT( 11) NOT NULL AUTO_INCREMENT,
username VARCHAR(255) NOT NULL UNIQUE,
password VARCHAR(255) NOT NULL,
created_at DATETIME NOT NULL,
PRIMARY KEY (id)
);
Next, we need to write PHP code to connect to the MySQL database and verify the username and password. The following is a simple PHP code example:
//MySQL database connection information
$servername = "localhost";
$username = "root";
$password = "password";
$dbname = "test";
// Create a MySQL connection
$conn = new mysqli($servername, $username, $password, $dbname) ;
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Get the POST parameters Username and password
$username = $_POST["username"];
$password = $_POST["password"];
// Verify username and password
$sql = " SELECT * FROM users WHERE username='{$username}'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
$row = $result->fetch_assoc();
if (password_verify($password, $row["password"])) {
echo "登录成功";
} else {
echo "密码不正确";
}
} else {
echo "Username does not exist";
}
$conn->close();
?>
The main process of the above PHP code includes:
In order to simplify the process of user registration and adding new user records in the database, we can create a user registration page. In this page, we will ask the user to fill in their username and password, and pass this information to the PHP code we wrote previously through the POST method.
The following is an example of a simple user registration page:
In the above code, we use the