How can SQL injection vulnerabilities be mitigated when passing SESSION variables to SQL queries?

SQL injection vulnerabilities can be mitigated by using prepared statements with parameterized queries when passing SESSION variables to SQL queries. This approach helps prevent malicious SQL code from being injected into the query and executed by the database.

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

// Prepare a SQL query with a placeholder for the session variable
$stmt = $pdo->prepare("SELECT * FROM users WHERE username = :username");

// Bind the session variable to the placeholder
$stmt->bindParam(':username', $_SESSION['username']);

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

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