What are the potential security risks associated with directly displaying database information in PHP?

Displaying database information directly in PHP can expose sensitive data to potential attackers. This can include usernames, passwords, and other confidential information. To mitigate this risk, it is recommended to sanitize and validate the data before displaying it to the user. This can be done by using prepared statements or data filtering functions.

// Connect to the database
$pdo = new PDO("mysql:host=localhost;dbname=mydatabase", "username", "password");

// Prepare and execute a query
$stmt = $pdo->prepare("SELECT * FROM users WHERE id = :id");
$stmt->bindParam(':id', $id);
$stmt->execute();

// Fetch and display the data
while ($row = $stmt->fetch()) {
    echo htmlspecialchars($row['username']); // Sanitize the data before displaying
}