How can the PHP code be improved to properly check if the username already exists in the database?
The PHP code can be improved by using a prepared statement to check if the username already exists in the database. This helps prevent SQL injection attacks and ensures the query is executed safely. By binding parameters and executing the query, we can efficiently determine if the username is already in use.
<?php
// Check if the username already exists in the database
$stmt = $pdo->prepare("SELECT username FROM users WHERE username = :username");
$stmt->bindParam(':username', $username);
$stmt->execute();
$user = $stmt->fetch();
if($user) {
echo "Username already exists.";
} else {
echo "Username is available.";
}
?>