What are the risks of directly outputting database query results to HTML without proper sanitization or validation in PHP?
Outputting database query results directly to HTML without proper sanitization or validation in PHP can lead to SQL injection attacks, where malicious code can be injected into the query and executed. To prevent this, it is important to sanitize the data before displaying it on the webpage. This can be done using functions like htmlspecialchars() to escape special characters and prevent code injection.
// Retrieve data from the database
$query = "SELECT * FROM users";
$result = mysqli_query($connection, $query);
// Output the data to HTML after sanitizing it
echo "<table>";
while($row = mysqli_fetch_assoc($result)) {
echo "<tr>";
echo "<td>" . htmlspecialchars($row['username']) . "</td>";
echo "<td>" . htmlspecialchars($row['email']) . "</td>";
echo "</tr>";
}
echo "</table>";