What potential security risks are associated with displaying MySQL query results directly on a webpage in PHP?

Displaying MySQL query results directly on a webpage in PHP can expose sensitive information such as database structure, user credentials, and other confidential data to potential attackers. To mitigate this security risk, it is recommended to sanitize and validate the data before displaying it on the webpage.

// Connect to MySQL database
$connection = mysqli_connect("localhost", "username", "password", "database");

// Run query
$query = "SELECT * FROM table";
$result = mysqli_query($connection, $query);

// Sanitize and validate data before displaying
while($row = mysqli_fetch_assoc($result)) {
    $safeData = htmlspecialchars($row['column_name']);
    echo "<p>$safeData</p>";
}

// Close connection
mysqli_close($connection);