How can SQL injection vulnerabilities be mitigated when executing SQL queries in PHP code?

SQL injection vulnerabilities can be mitigated by using prepared statements with parameterized queries in PHP code. This approach separates the SQL query logic from the user input, preventing malicious SQL code from being injected into the query.

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

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

// Bind the parameter value
$stmt->bindParam(':username', $_POST['username']);

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

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