What are the best practices for ensuring data integrity in PHP when dealing with unique usernames in a database?

When dealing with unique usernames in a database, it is important to ensure data integrity by checking for existing usernames before inserting a new one. One way to do this is by querying the database to see if the username already exists, and then only inserting the new username if it is unique. Additionally, using prepared statements and parameterized queries can help prevent SQL injection attacks.

// Check if the username already exists in the database
$username = $_POST['username'];
$stmt = $pdo->prepare("SELECT COUNT(*) FROM users WHERE username = :username");
$stmt->bindParam(':username', $username);
$stmt->execute();
$count = $stmt->fetchColumn();

// If the username is unique, insert it into the database
if($count == 0) {
    $stmt = $pdo->prepare("INSERT INTO users (username) VALUES (:username)");
    $stmt->bindParam(':username', $username);
    $stmt->execute();
    echo "Username successfully inserted!";
} else {
    echo "Username already exists!";
}