What best practices should be followed when using PHP to loop through database results and output them in HTML tables?
When looping through database results and outputting them in HTML tables using PHP, it is important to follow best practices to ensure clean and efficient code. One common approach is to use a while loop to fetch each row from the database result set and then output the data within HTML table rows. It is also recommended to sanitize the data to prevent SQL injection attacks and format the output for better readability.
<?php
// Assume $result is the database result set
echo "<table>";
echo "<tr><th>ID</th><th>Name</th><th>Email</th></tr>";
while($row = mysqli_fetch_assoc($result)) {
echo "<tr>";
echo "<td>" . $row['id'] . "</td>";
echo "<td>" . htmlspecialchars($row['name']) . "</td>";
echo "<td>" . htmlspecialchars($row['email']) . "</td>";
echo "</tr>";
}
echo "</table>";
?>
Keywords
Related Questions
- What best practices should be followed when using ftp_chmod() in PHP?
- What are the potential advantages and disadvantages of using PHP for form handling and calculations compared to JavaScript?
- How can PHP be used to generate and save PDF files in the background without opening them immediately, allowing the program to continue running uninterrupted?