How can context switching between SQL and HTML be managed effectively to prevent vulnerabilities like SQL injection and cross-site scripting?

To effectively manage context switching between SQL and HTML to prevent vulnerabilities like SQL injection and cross-site scripting, it is important to use parameterized queries for SQL statements and properly escape user input when outputting data in HTML.

// Example of using parameterized queries to prevent SQL injection
$stmt = $pdo->prepare('SELECT * FROM users WHERE username = :username');
$stmt->bindParam(':username', $username);
$stmt->execute();

// Example of escaping user input when outputting data in HTML
echo htmlspecialchars($userInput, ENT_QUOTES, 'UTF-8');