简体   繁体   中英

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 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; 

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

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

The question is old, but this is how it can be done now with mysqli_*

//Function to generate a HTML table from a SQL query
function myTable($obConn,$sql)
{
    $rsResult = mysqli_query($obConn, $sql) or die(mysqli_error($obConn));
    if(mysqli_num_rows($rsResult)>0)
    {
        //We start with header
        echo "<table width=\"100%\" border=\"0\" cellspacing=\"2\" cellpadding=\"0\"><tr align=\"center\" bgcolor=\"#CCCCCC\">";
        $i = 0;
        while ($i < mysqli_num_fields($rsResult)){
           $field = mysqli_fetch_field_direct($rsResult, $i);
           $fieldName=$field->name;
           echo "<td><strong>$fieldName</strong></td>";
           $i = $i + 1;
        }
        echo "</tr>";

        //We dump info
        $bolWhite=true;
        while ($row = mysqli_fetch_assoc($rsResult)) {
            echo $bolWhite ? "<tr bgcolor=\"#CCCCCC\">" : "<tr bgcolor=\"#FFF\">";
            $bolWhite=!$bolWhite;
            foreach($row as $data) {
                echo "<td>$data</td>";
            }
            echo "</tr>";
        }
        echo "</table>";
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM