How can PHP developers prevent SQL injection when using variables in SQL statements?

To prevent SQL injection when using variables in SQL statements, PHP developers can use prepared statements with parameterized queries. This method separates the SQL query logic from the user input, preventing malicious SQL code from being executed.

// Using prepared statements to prevent SQL injection
$stmt = $pdo->prepare("SELECT * FROM users WHERE username = :username");
$stmt->bindParam(':username', $username);
$stmt->execute();