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

SQL injection vulnerabilities can be mitigated when executing dynamic queries in PHP by using prepared statements with parameterized queries. This method separates the SQL query from the user input, preventing malicious SQL code from being executed. By binding parameters to the query, the database engine can distinguish between the actual query and the user input, ensuring a secure execution.

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

// User input
$userInput = $_POST['user_input'];

// Prepare a SQL query 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', $userInput);

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

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

// Process the results
foreach ($results as $row) {
    echo $row['username'] . "<br>";
}