What are some best practices for comparing user input during registration with existing database entries in PHP?

When a user registers on a website, it's important to compare their input (such as email or username) with existing entries in the database to ensure uniqueness. One way to do this in PHP is to query the database to check if the user input already exists before allowing the registration to proceed.

// Assuming you have already established a database connection

// Get user input from registration form
$email = $_POST['email'];

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

if(mysqli_num_rows($result) > 0) {
    // Email already exists, display an error message
    echo "Email already exists, please choose a different one.";
} else {
    // Proceed with user registration
    // Insert user data into the database
}