How can the user registration script be improved to ensure successful registration in the database?

Issue: The user registration script needs to ensure that the user's input data is properly validated and sanitized before inserting it into the database to prevent SQL injection attacks and ensure successful registration.

// Validate and sanitize user input data before inserting into the database
$username = filter_var($_POST['username'], FILTER_SANITIZE_STRING);
$email = filter_var($_POST['email'], FILTER_SANITIZE_EMAIL);
$password = password_hash($_POST['password'], PASSWORD_DEFAULT);

// Insert sanitized data into the database
$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);

if($stmt->execute()){
    echo "User registered successfully!";
} else {
    echo "Error registering user. Please try again.";
}