What are the best practices for dynamically generating HTML tables in PHP based on database results?
When dynamically generating HTML tables in PHP based on database results, it is important to separate the logic of fetching data from the database and generating the HTML table. This can be achieved by fetching the data into an array and then using a loop to iterate over the array and output the table rows. Additionally, using HTML table tags within PHP echo statements can help in creating a clean and readable code.
<?php
// Fetch data from the database
$data = array(
array("Name" => "John Doe", "Age" => 30, "City" => "New York"),
array("Name" => "Jane Smith", "Age" => 25, "City" => "Los Angeles"),
array("Name" => "Alice Johnson", "Age" => 35, "City" => "Chicago")
);
// Generate HTML table
echo "<table>";
echo "<tr><th>Name</th><th>Age</th><th>City</th></tr>";
foreach($data as $row) {
echo "<tr>";
echo "<td>".$row['Name']."</td>";
echo "<td>".$row['Age']."</td>";
echo "<td>".$row['City']."</td>";
echo "</tr>";
}
echo "</table>";
?>