Currently, I'm storing MySQL query results in an array of objects, where each object represents a row that matches the query. Later, I run through two foreach loops to extract the results - in the example below, they are outputted as a dynamically-generated HTML table.
My question: Is it possible to obtain the column names from the query result object? My goal is to be able to dynamically generate the table headings, which my HTML table is currently lacking.
Thanks!
$data = array();
$result = db_query("SELECT column1, column2 FROM table");
while ($obj= db_fetch_object($result)) {
array_push($data, $obj);
}
$ret = "<table>";
foreach ($data as $row) {
$ret .= "<tr>";
foreach ($row as $field) {
$ret .= "<td>$field</td>";
}
$ret .= "</tr>";
}
$ret .= "</table>";
return $ret;
You can use this function http://php.net/manual/en/function.mysql-fetch-field.php