What potential pitfalls should be considered when using PHP for querying databases?

Potential pitfalls when using PHP for querying databases include SQL injection attacks, improper error handling leading to security vulnerabilities, and inefficient queries causing performance issues. To mitigate these risks, it is important to use parameterized queries, sanitize user input, implement proper error handling, and optimize queries for better performance.

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

```php
// Sanitizing user input to prevent SQL injection attacks
$username = filter_var($_POST['username'], FILTER_SANITIZE_STRING);
```

```php
// Implementing proper error handling to prevent security vulnerabilities
try {
    $pdo = new PDO($dsn, $username, $password);
} catch (PDOException $e) {
    echo "Connection failed: " . $e->getMessage();
}
```

```php
// Optimizing queries for better performance
$stmt = $pdo->query("SELECT * FROM users WHERE id = $id");
$stmt->execute();