What is the best practice for checking if a username and password exist in a database for a login form in PHP?

When checking if a username and password exist in a database for a login form in PHP, it is best practice to use prepared statements to prevent SQL injection attacks. This involves using parameterized queries to safely pass user input to the database. Additionally, passwords should be securely hashed before storing them in the database to enhance security.

<?php
// Assuming $username and $password are the user input from the login form

// Connect to database
$pdo = new PDO('mysql:host=localhost;dbname=your_database', 'username', 'password');

// Prepare SQL statement
$stmt = $pdo->prepare("SELECT * FROM users WHERE username = :username");
$stmt->bindParam(':username', $username);
$stmt->execute();
$user = $stmt->fetch();

if ($user && password_verify($password, $user['password'])) {
    // Login successful
    echo "Login successful";
} else {
    // Login failed
    echo "Login failed";
}
?>