What best practices should be followed when iterating over database query results and generating HTML output in PHP?
When iterating over database query results and generating HTML output in PHP, it is important to separate your PHP logic from your HTML presentation. This can be achieved by using a templating engine like Twig or simply by keeping your PHP code separate from your HTML code. Additionally, make sure to properly escape any user input to prevent cross-site scripting attacks.
<?php
// Query the database
$query = "SELECT * FROM users";
$result = mysqli_query($connection, $query);
// Iterate over the results and generate HTML output
while ($row = mysqli_fetch_assoc($result)) {
echo "<div>Name: " . htmlspecialchars($row['name']) . "</div>";
echo "<div>Email: " . htmlspecialchars($row['email']) . "</div>";
}
?>