How can code injection be prevented in PHP forms?

Code injection in PHP forms can be prevented by using prepared statements with parameterized queries when interacting with a database. This helps to sanitize user input and prevent malicious code from being executed. Additionally, input validation should be implemented to ensure that only expected data types and formats are accepted.

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