What are the potential risks of SQL injection in PHP code and how can they be mitigated?

SQL injection is a common attack where malicious SQL statements are inserted into input fields to manipulate the database. To mitigate this risk in PHP code, developers should use prepared statements with parameterized queries instead of directly concatenating user input with SQL queries.

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