How can the use of HTML tags within PHP code affect the display of data from a MySQL database?

When using HTML tags within PHP code to display data from a MySQL database, it is important to properly escape the data to prevent any potential security vulnerabilities such as cross-site scripting attacks. One way to solve this issue is by using the htmlspecialchars() function in PHP to convert special characters to HTML entities before displaying the data on the webpage.

<?php
// Fetch data from MySQL database
$data = "<script>alert('XSS attack');</script>";
// Escape HTML tags before displaying the data
echo htmlspecialchars($data);
?>