How can SQL injection vulnerabilities be mitigated when constructing dynamic queries in PHP for database operations?

SQL injection vulnerabilities can be mitigated by using prepared statements and parameterized queries when constructing dynamic queries in PHP for database operations. 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=my_database', 'username', 'password');

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

// Bind parameters to the placeholders
$stmt->bindParam(':username', $_POST['username']);

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

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