What are some best practices for dynamically generating HTML tables from DB query results in PHP?

When dynamically generating HTML tables from DB query results in PHP, it is best to separate the logic of querying the database and generating the HTML table. This helps to keep your code organized and easier to maintain. Additionally, consider using loops to iterate through the query results and populate the table rows dynamically.

// Assume $queryResult contains the results of your database query

// Start building the HTML table
$html = '<table>';

// Add table headers
$html .= '<tr>';
foreach ($queryResult[0] as $key => $value) {
    $html .= '<th>' . $key . '</th>';
}
$html .= '</tr>';

// Add table rows
foreach ($queryResult as $row) {
    $html .= '<tr>';
    foreach ($row as $value) {
        $html .= '<td>' . $value . '</td>';
    }
    $html .= '</tr>';
}

// Close the table
$html .= '</table>';

// Output the HTML table
echo $html;