How can SQL injection vulnerabilities be mitigated in PHP code that interacts with a database?

SQL injection vulnerabilities can be mitigated 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 injected into the query. By binding parameters to the query, the database engine treats them as data rather than executable SQL code, effectively protecting against 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 AND password = :password");

// Bind parameters to the query
$stmt->bindParam(':username', $username);
$stmt->bindParam(':password', $password);

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

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