What are common pitfalls to avoid when implementing username uniqueness in PHP registration forms?

One common pitfall to avoid when implementing username uniqueness in PHP registration forms is not checking if the username already exists in the database before allowing a user to register with that username. To solve this issue, you can perform a query to check if the username already exists in the database before allowing the user to proceed with the registration.

// Check if the username already exists in the database
$username = $_POST['username'];
$query = "SELECT * FROM users WHERE username = '$username'";
$result = mysqli_query($conn, $query);

if(mysqli_num_rows($result) > 0){
    // Username already exists, display an error message
    echo "Username already exists. Please choose a different username.";
} else {
    // Username is unique, proceed with the registration process
    // Add code to insert the user into the database
}