How can PHP code be optimized to enhance security in guestbook applications?

To enhance security in guestbook applications, PHP code can be optimized by implementing input validation, using prepared statements to prevent SQL injection attacks, and escaping output to prevent cross-site scripting attacks.

// Input validation
$name = filter_input(INPUT_POST, 'name', FILTER_SANITIZE_STRING);
$message = filter_input(INPUT_POST, 'message', FILTER_SANITIZE_STRING);

// Prepared statements to prevent SQL injection
$stmt = $pdo->prepare("INSERT INTO guestbook (name, message) VALUES (:name, :message)");
$stmt->bindParam(':name', $name);
$stmt->bindParam(':message', $message);
$stmt->execute();

// Escaping output to prevent cross-site scripting
echo htmlentities($message, ENT_QUOTES, 'UTF-8');