How can SQL injection vulnerabilities be prevented when using dynamic values in SQL queries in PHP?

SQL injection vulnerabilities can be prevented by using prepared statements with parameterized queries in PHP. This approach ensures that user input is treated as data rather than executable code, making it impossible for attackers to inject malicious SQL commands.

// Example of using prepared statements to prevent SQL injection
$pdo = new PDO('mysql:host=localhost;dbname=mydatabase', 'username', 'password');
$stmt = $pdo->prepare('SELECT * FROM users WHERE username = :username');
$stmt->bindParam(':username', $username);
$stmt->execute();
$results = $stmt->fetchAll();