What is the recommended approach for implementing a login form in PHP that checks user credentials against a database?

To implement a login form in PHP that checks user credentials against a database, you should first create a form with fields for username and password. Upon form submission, retrieve the entered credentials and query the database to check if the user exists and the password matches. If the credentials are valid, set a session variable to indicate the user is logged in.

<?php
session_start();

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

    // Connect to database
    $conn = new mysqli("localhost", "username", "password", "database");

    // Check if user exists and password matches
    $query = "SELECT * FROM users WHERE username = '$username' AND password = '$password'";
    $result = $conn->query($query);

    if ($result->num_rows == 1) {
        $_SESSION['loggedin'] = true;
        header("Location: dashboard.php");
    } else {
        echo "Invalid username or password";
    }

    $conn->close();
}
?>

<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
    <input type="text" name="username" placeholder="Username" required><br>
    <input type="password" name="password" placeholder="Password" required><br>
    <input type="submit" value="Login">
</form>