Skip to content
PHP Logo

How can PHP developers handle dynamic table creation based on the results of variable SQL queries?

When handling dynamic table creation based on the results of variable SQL queries in PHP, developers can use the `mysqli_fetch_fields()` function to get the field names from the query result and dynamically generate the table structure. By iterating over the field names, developers can create the table headers and then populate the table rows with the query results.

php
// Assuming $queryResult contains the result of the variable SQL query

// Get the field names from the query result
$fields = mysqli_fetch_fields($queryResult);

// Start creating the table structure
echo "<table><tr>";
// Create table headers
foreach ($fields as $field) {
    echo "<th>" . $field->name . "</th>";
}
echo "</tr>";

// Populate table rows with query results
while ($row = mysqli_fetch_assoc($queryResult)) {
    echo "<tr>";
    foreach ($fields as $field) {
        echo "<td>" . $row[$field->name] . "</td>";
    }
    echo "</tr>";
}

echo "</table>";