How can the context switch be properly handled in PHP to prevent vulnerabilities like SQL injection?

To prevent vulnerabilities like SQL injection in PHP, it is important to properly handle the context switch when interacting with databases. This can be achieved by using prepared statements or parameterized queries, which allow the database engine to distinguish between SQL code and user input. By binding parameters to placeholders in the SQL query, the database can safely execute the query without risking injection attacks.

// Establish a connection to the database
$pdo = new PDO('mysql:host=localhost;dbname=mydatabase', 'username', 'password');

// Prepare a SQL query with placeholders for user input
$stmt = $pdo->prepare('SELECT * FROM users WHERE username = :username');

// Bind the user input to the placeholders
$stmt->bindParam(':username', $_POST['username']);

// Execute the query
$stmt->execute();

// Fetch the results
$results = $stmt->fetchAll();