How can SQL injection vulnerabilities be mitigated in PHP code when querying user data from a database?

SQL injection vulnerabilities can be mitigated in PHP code by using prepared statements with parameterized queries. This approach ensures that user input is treated as data rather than executable code, preventing malicious SQL injection attacks. Example PHP code snippet using prepared statements to query user data from a database:

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

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

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

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

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

// Process the results
foreach ($results as $row) {
    echo $row['username'] . '<br>';
}
?>