How can you check if a username is already taken in a PHP registration form?

To check if a username is already taken in a PHP registration form, you can query your database to see if the username already exists. If it does, you can display an error message to the user prompting them to choose a different username. You can use PHP and SQL to accomplish this task.

// Assuming you have already established a database connection

$username = $_POST['username'];

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

if(mysqli_num_rows($result) > 0){
    // Username already exists, display an error message
    echo "Username is already taken. Please choose a different username.";
} else {
    // Username is available, proceed with registration
    // Add the username to the database or perform other necessary actions
}