What is the best practice for checking if a username already exists in a database using PHP?

When checking if a username already exists in a database using PHP, the best practice is to use a prepared statement to prevent SQL injection attacks. You can query the database to check if the username already exists and then fetch the result to determine if it is already in use.

<?php
// Assume $username is the username to check
$stmt = $pdo->prepare("SELECT COUNT(*) FROM users WHERE username = :username");
$stmt->bindParam(':username', $username);
$stmt->execute();
$count = $stmt->fetchColumn();

if ($count > 0) {
    echo "Username already exists";
} else {
    echo "Username is available";
}
?>