How can MySQL databases be utilized to create a password-protected area on a website?

To create a password-protected area on a website using MySQL databases, you can store user credentials (such as usernames and passwords) in a table within the database. When a user tries to access the protected area, their inputted credentials can be checked against the database to verify their identity. If the credentials match, the user can be granted access to the protected area.

<?php
// Connect to MySQL database
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database_name";
$conn = new mysqli($servername, $username, $password, $dbname);

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

// Retrieve user input
$username = $_POST['username'];
$password = $_POST['password'];

// Query database to check if user exists
$sql = "SELECT * FROM users WHERE username='$username' AND password='$password'";
$result = $conn->query($sql);

// If user exists, grant access
if ($result->num_rows > 0) {
    echo "Access granted!";
} else {
    echo "Access denied. Please check your credentials.";
}

// Close database connection
$conn->close();
?>