What are some best practices for creating a login system in PHP that checks user credentials against a MySQL database?

Issue: When creating a login system in PHP that checks user credentials against a MySQL database, it is important to securely hash passwords before storing them in the database and compare the hashed password during the login process to ensure data security.

// 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);
}

// Validate user credentials
$username = $_POST['username'];
$password = $_POST['password'];

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

if ($result->num_rows > 0) {
    $row = $result->fetch_assoc();
    if (password_verify($password, $row['password'])) {
        // Login successful
        echo "Login successful!";
    } else {
        // Invalid password
        echo "Invalid password!";
    }
} else {
    // User not found
    echo "User not found!";
}

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