What are some potential pitfalls to be aware of when handling database results in PHP?

One potential pitfall when handling database results in PHP is not properly sanitizing the data before outputting it, which can lead to security vulnerabilities such as SQL injection attacks. To mitigate this risk, always use prepared statements or parameterized queries when interacting with the database to prevent malicious input from being executed as SQL commands.

// Example of using prepared statements to handle database results securely
$stmt = $pdo->prepare('SELECT * FROM users WHERE username = :username');
$stmt->bindParam(':username', $username);
$stmt->execute();
$results = $stmt->fetchAll();

foreach ($results as $row) {
    // Output sanitized data
    echo htmlspecialchars($row['username']);
}