What functions or methods should be used in PHP to properly handle context switches to HTML and SQL?

To properly handle context switches to HTML and SQL in PHP, you should use functions like htmlspecialchars() to escape HTML entities and prevent XSS attacks when outputting user input in HTML, and prepared statements to safely handle SQL queries and prevent SQL injection attacks.

// Escaping HTML entities when outputting user input in HTML
$userInput = "<script>alert('XSS attack');</script>";
$escapedInput = htmlspecialchars($userInput, ENT_QUOTES, 'UTF-8');
echo "<p>User input: $escapedInput</p>";

// Using prepared statements to safely handle SQL queries
$pdo = new PDO("mysql:host=localhost;dbname=mydatabase", "username", "password");
$stmt = $pdo->prepare("SELECT * FROM users WHERE username = :username");
$stmt->bindParam(':username', $username, PDO::PARAM_STR);
$username = "admin'; DROP TABLE users;--";
$stmt->execute();