In what way can the database query and email sending functionality be optimized in the PHP script to avoid potential errors?

To optimize the database query and email sending functionality in the PHP script to avoid potential errors, you can use prepared statements for database queries to prevent SQL injection attacks and sanitize user inputs before sending emails to prevent email injection attacks. Additionally, you can implement error handling to catch any exceptions that may occur during database queries or email sending processes.

// Database query with prepared statement
$stmt = $pdo->prepare("SELECT * FROM users WHERE username = ?");
$stmt->execute([$username]);
$result = $stmt->fetch();

// Sanitize email input before sending
$clean_email = filter_var($email, FILTER_SANITIZE_EMAIL);

// Send email with error handling
if (mail($clean_email, $subject, $message)) {
    echo "Email sent successfully";
} else {
    echo "Failed to send email";
}