What are common errors encountered when writing SQL queries in PHP, and how can they be resolved?

One common error when writing SQL queries in PHP is not properly escaping user input, which can lead to SQL injection attacks. To prevent this, use prepared statements with parameterized queries to sanitize input. Another common error is not checking for errors returned by the database when executing queries, which can lead to unexpected behavior. Always check for errors and handle them appropriately.

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

// Example of checking for errors when executing queries
if(!$stmt){
    die("Error executing query: " . $pdo->errorInfo());
}