What best practices should be followed when handling user input validation and database interactions in PHP registration scripts to avoid errors and ensure data integrity?

Issue: To ensure data integrity and prevent errors in PHP registration scripts, it is essential to properly handle user input validation and database interactions. This includes sanitizing and validating user input to prevent SQL injection attacks, checking for duplicate entries before inserting data into the database, and using prepared statements to securely interact with the database. PHP Code Snippet:

// Validate user input
$username = filter_var($_POST['username'], FILTER_SANITIZE_STRING);
$email = filter_var($_POST['email'], FILTER_VALIDATE_EMAIL);
$password = password_hash($_POST['password'], PASSWORD_DEFAULT);

// Check for duplicate entries
$stmt = $pdo->prepare("SELECT * FROM users WHERE email = :email");
$stmt->bindParam(':email', $email);
$stmt->execute();

if ($stmt->rowCount() > 0) {
    echo "Email already exists";
} else {
    // Insert data into the database using prepared statements
    $stmt = $pdo->prepare("INSERT INTO users (username, email, password) VALUES (:username, :email, :password)");
    $stmt->bindParam(':username', $username);
    $stmt->bindParam(':email', $email);
    $stmt->bindParam(':password', $password);
    $stmt->execute();
    echo "Registration successful";
}