How To Make Login Page In Php Mysql

Creating a login page is an essential part of any dynamic website. It allows users to access personalized content and ensures the security of sensitive information. In this article, I will guide you through the process of creating a login page using PHP and MySQL.

Setting Up the Database

Before we dive into coding the login page, we need to set up the database to store user credentials. Start by creating a new database in MySQL and then create a table to store user information. The table should have columns for username, password, and any other relevant user details.


CREATE DATABASE mylogin_db;
USE mylogin_db;
CREATE TABLE users (
id INT AUTO_INCREMENT PRIMARY KEY,
username VARCHAR(50) NOT NULL,
password VARCHAR(50) NOT NULL,
email VARCHAR(100) NOT NULL
);

Creating the HTML Form

Now, let’s create the HTML form for the login page. We will use the <form> element to collect user input and send it to the PHP script for validation. The form should contain fields for username and password.


<form method="POST" action="login.php">
<label for="username">Username:</label>
<input type="text" id="username" name="username" required><br>

<label for="password">Password:</label>
<input type="password" id="password" name="password" required><br>

<input type="submit" value="Login">
</form>

Validating the User Input

Next, let’s create the PHP script that will validate the user input and check if the entered credentials match with the ones stored in the database. We will use the mysqli extension to connect to the MySQL database and perform the necessary queries.


connect_error) {
die("Connection failed: " . $conn->connect_error);
}

if ($_SERVER["REQUEST_METHOD"] == "POST") {
$username = $_POST['username'];
$password = $_POST['password'];

$sql = "SELECT * FROM users WHERE username = '$username' AND password = '$password'";
$result = $conn->query($sql);

if ($result->num_rows == 1) {
echo "Login successful!";
} else {
echo "Invalid username or password.";
}
}

$conn->close();
?>

Adding Security Measures

When dealing with user authentication, it’s crucial to implement proper security measures to protect against common attacks, such as SQL injection and password hashing. While this article focuses on the basics, it’s important to research and implement additional security measures based on your specific needs.

Conclusion

Creating a login page in PHP and MySQL is an essential skill for web developers. By following the steps outlined in this article, you can create a secure and functional login page for your website. Remember to always prioritize security and stay updated on the latest best practices.

For a live example and to see the code in action, you can check out my personal login page on my website: example.com/login.