In what ways can PHP developers optimize their code to prevent SQL injection vulnerabilities when querying MySQL databases in PHP applications?

To prevent SQL injection vulnerabilities when querying MySQL databases in PHP applications, PHP developers can utilize prepared statements with parameterized queries. This approach separates SQL logic from user input, ensuring that input is treated as data rather than executable code. By binding parameters to placeholders in the SQL query, developers can prevent malicious SQL injection attacks.

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

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

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

// Execute the prepared statement
$stmt->execute();

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