How can SQL injection vulnerabilities be prevented in PHP code, especially when constructing queries with user input?

SQL injection vulnerabilities can be prevented in PHP code by using prepared statements with parameterized queries. This approach separates the SQL query logic from the user input, preventing malicious input from altering the query's structure. By binding parameters to placeholders in the query, the database server can distinguish between 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 parameterized query
$stmt = $pdo->prepare('SELECT * FROM users WHERE username = :username');

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

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

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