What are common errors when querying a database in PHP?

Common errors when querying a database in PHP include using incorrect SQL syntax, not properly sanitizing user input which can lead to SQL injection attacks, and not handling errors or exceptions properly. To solve these issues, always use prepared statements to prevent SQL injection, double-check your SQL syntax, and implement error handling to catch any potential issues that may arise during the query execution.

// Example of using prepared statements to prevent SQL injection
$pdo = new PDO("mysql:host=localhost;dbname=mydatabase", "username", "password");

$stmt = $pdo->prepare("SELECT * FROM users WHERE username = :username");
$stmt->bindParam(':username', $username);
$stmt->execute();

// Example of error handling
if(!$stmt) {
    echo "Error executing query";
    exit;
}

// Example of fetching results
while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
    echo $row['username'] . "<br>";
}