What are some common pitfalls to avoid when writing PHP code?

One common pitfall to avoid when writing PHP code is not properly sanitizing user input, which can leave your application vulnerable to security risks such as SQL injection attacks. To solve this issue, always use prepared statements when interacting with a database to prevent malicious input from being executed as SQL queries.

// Example of using prepared statements to sanitize user input
$stmt = $pdo->prepare('SELECT * FROM users WHERE username = :username');
$stmt->execute(['username' => $username]);
$user = $stmt->fetch();