How can one prevent SQL injection vulnerabilities when dynamically constructing SQL queries in PHP as shown in the example?

To prevent SQL injection vulnerabilities when dynamically constructing SQL queries in PHP, one should use prepared statements with bound parameters. This method separates the SQL query from the user input, preventing malicious input from altering the query's structure. By using prepared statements, the input is treated as data rather than executable SQL code, effectively mitigating the risk of SQL injection attacks.

// Connect to the database
$pdo = new PDO('mysql:host=localhost;dbname=mydatabase', 'username', 'password');

// Prepare a SQL statement with a placeholder for the user input
$stmt = $pdo->prepare("SELECT * FROM users WHERE username = :username");

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

// Execute the prepared statement
$stmt->execute();

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