What best practices should be followed when writing PHP code to compare email addresses in a database and prevent multiple registrations?
When comparing email addresses in a database to prevent multiple registrations, it is important to first sanitize and validate the input to ensure it is a properly formatted email address. Then, query the database to check if the email address already exists. If it does, display an error message to the user. If it does not exist, proceed with the registration process.
$email = filter_var($_POST['email'], FILTER_SANITIZE_EMAIL);
// Check if the email address already exists in the database
$stmt = $pdo->prepare("SELECT COUNT(*) FROM users WHERE email = :email");
$stmt->bindParam(':email', $email);
$stmt->execute();
$count = $stmt->fetchColumn();
if ($count > 0) {
echo "Email address already exists. Please use a different email.";
} else {
// Proceed with registration process
}