Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Obtain column names from MySQL query object (PHP)

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; 
like image 531
kaspnord Avatar asked Nov 20 '25 04:11

kaspnord


1 Answers

There is function to retreive column name. Please check with this link :

http://php.net/manual/en/function.mysql-fetch-field.php

like image 143
Sabari Avatar answered Nov 21 '25 16:11

Sabari