What is the recommended method to check if a username already exists in a PHP database?

To check if a username already exists in a PHP database, you can query the database to see if any rows match the input username. If a row is returned, it means the username already exists. You can use a SELECT query with a WHERE clause to search for the username in the database table.

<?php
// Assume $username is the input username
$username = $_POST['username'];

// Connect to the database
$connection = new mysqli('localhost', 'username', 'password', 'database');

// Check if the username already exists
$query = "SELECT * FROM users WHERE username = '$username'";
$result = $connection->query($query);

if ($result->num_rows > 0) {
    echo "Username already exists";
} else {
    echo "Username is available";
}

// Close the database connection
$connection->close();
?>