What are some best practices for creating a login system in PHP for a community website?

Issue: Creating a secure login system in PHP for a community website is essential to protect user data and ensure only authorized users can access certain features. Code snippet:

<?php
session_start();

// Check if the form is submitted
if($_SERVER["REQUEST_METHOD"] == "POST"){
    // Include database connection
    require_once "db_connection.php";

    // Get user input from the login form
    $username = $_POST['username'];
    $password = $_POST['password'];

    // Sanitize user input
    $username = mysqli_real_escape_string($conn, $username);
    $password = mysqli_real_escape_string($conn, $password);

    // Query the database for the user
    $query = "SELECT * FROM users WHERE username='$username' AND password='$password'";
    $result = mysqli_query($conn, $query);

    // Check if the user exists
    if(mysqli_num_rows($result) == 1){
        // User is authenticated, create session
        $_SESSION['username'] = $username;
        header("Location: dashboard.php");
    } else {
        // Invalid credentials, show error message
        echo "Invalid username or password";
    }
}
?>