How can SQL injection vulnerabilities be prevented in PHP/MySQL queries?

SQL injection vulnerabilities can be prevented in PHP/MySQL queries by using prepared statements with parameterized queries. This method separates SQL code from user input, preventing malicious SQL code from being executed. Prepared statements automatically escape input values, making it impossible for attackers to inject SQL code into queries.

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

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

// Bind the parameter value
$stmt->bindParam(':username', $_POST['username']);

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

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