How can SQL injection vulnerabilities be addressed in PHP code that directly inserts variables into database queries?

SQL injection vulnerabilities can be addressed in PHP code by using prepared statements with parameterized queries. This approach separates the SQL query logic from the user input, preventing malicious SQL code from being executed. By binding parameters to the query, the database engine can distinguish between SQL code and data, effectively mitigating the risk of SQL injection attacks.

// 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 parameter to the query
$stmt->bindParam(':username', $username);

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

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