开发者

Get field names from database result

Here I want to fetch the field names from the table name which is stored in the variable $table. And want to make a table headers of the field names. What's wrong with this approach I tried:

<?php

     $sql=mysql_query("show fields from $table");
     if(mysql_num_rows($sql))
     while($res = 开发者_Python百科mysql_fetch_object($sql))
     {
     ?>
     <th><?php echo $res->field; ?></th>


     <?
      }
      else
      {
      echo "No data to display";
      }



        ?>


$printTHs = true;
while($res = mysql_fetch_assoc($sql))
{
    if ($printTHs)
    {
        printTableHeader($res);
        $printTHs= false;
    }

    echo "<tr>";

    foreach($res as $val)
    {
        echo "<td>" . $val . "</td>";
    }

    echo "</tr>";

}

function printTableHeader($res)
{

    echo "<tr>";

    foreach($res as $col => $val)
    {
        echo "<th>" . $col . "</th>";
    }

    echo "</tr>";
}


The query has to be

$sql=mysql_query("show columns from $table"); 


Use mysql_fetch_assoc() and then get the keys using array_keys(). This will return an array with all the keys.

Use foreach() to get your table headers


Not the optimal solution, but would do it:

$results = mysql_query('SELECT * FROM ' . $table);
if (mysql_num_rows($results))
{
    echo '<table>';
    $first = TRUE;

    while ($row = mysql_fetch_assoc($results))
    {
        if ($first = TRUE)
        {
            echo '<tr>';

            foreach ($row as $k => $v)
                echo '<th>' . $k . '</th>';

            echo '</tr>';
            $first = FALSE;
        }

        echo '<tr>';

        foreach ($row as $column)
            echo '<td>' . $column . '</td>';

        echo '</tr>';
    }

    echo '</table>';
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜