How can using htmlentities() or htmlspecialchars() in PHP affect the data stored in a MySQL database when outputting it as HTML?

When storing user input in a MySQL database, it is important to sanitize the data to prevent SQL injection attacks. However, when outputting this data as HTML, using htmlentities() or htmlspecialchars() can help prevent Cross-Site Scripting (XSS) attacks by encoding special characters. This ensures that the data is displayed correctly in the browser without executing any malicious scripts embedded in the input.

<?php
// Retrieve data from MySQL database
$data = $row['column_name'];

// Output the data with htmlentities() to prevent XSS attacks
echo htmlentities($data);
?>