What are common pitfalls when using PHP to query a database and how can they be avoided?

One common pitfall when using PHP to query a database is not properly sanitizing user input, which can lead to SQL injection attacks. To avoid this, always use parameterized queries or prepared statements to securely pass user input to the database.

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