How can PHP be used to check if a username is already taken before saving it to a MySQL database?

To check if a username is already taken before saving it to a MySQL database, you can query the database to see if any rows already exist with the given username. If a row is returned, then the username is taken and the user should be prompted to choose a different one. If no rows are returned, then the username is available to be saved.

<?php
$username = $_POST['username'];

// Connect to MySQL database
$connection = mysqli_connect("localhost", "username", "password", "database");

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

if(mysqli_num_rows($result) > 0) {
    echo "Username is already taken. Please choose a different one.";
} else {
    // Save username to database
    $insert_query = "INSERT INTO users (username) VALUES ('$username')";
    mysqli_query($connection, $insert_query);
    echo "Username saved successfully!";
}

// Close database connection
mysqli_close($connection);
?>