How can PHP developers prevent SQL injection vulnerabilities when executing MySQL queries?

SQL injection vulnerabilities can be prevented by using prepared statements with parameterized queries in PHP when executing MySQL queries. This helps to sanitize user input and prevent malicious SQL code from being injected into the query.

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

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

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

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

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