How can PHP be used to check if a username already exists in a MySQL database?

To check if a username already exists in a MySQL database using PHP, you can write a query to select the username from the database and then check if any rows are returned. If rows are returned, it means the username already exists. You can then use this information to display an error message to the user or take appropriate action.

<?php
// Assuming you have already established a connection to your MySQL database

$username = "desired_username";
$query = "SELECT * FROM users WHERE username = '$username'";
$result = mysqli_query($connection, $query);

if(mysqli_num_rows($result) > 0) {
    echo "Username already exists!";
} else {
    echo "Username is available.";
}
?>