What are the potential errors or pitfalls when echoing database values in PHP code?

Echoing database values directly in PHP code without proper sanitization can lead to security vulnerabilities such as SQL injection attacks. To avoid this, always use prepared statements or parameterized queries to safely retrieve and display database values.

// Example of using prepared statements to safely retrieve and display database values
$stmt = $pdo->prepare("SELECT name FROM users WHERE id = :id");
$stmt->bindParam(':id', $userId, PDO::PARAM_INT);
$stmt->execute();

$row = $stmt->fetch();
echo htmlspecialchars($row['name']);