问题描述:

Is there a better method to display data from a mysql table rather than having to create a table and then hardcode headers, and the fields within the table ?.

The psuedo code for what I am currently doing is

<table>

<tr>

<th>I am </th><th> harcoded</th>

</tr>

mysql loop through data

for all fields

while($row = mysql_fetch_assoc($result)){

<tr>

<td>data

</td>

<td>data

</td>

</tr>

}

</table>

网友答案:

I usually do something like this:

$header_done = false;
while($rs = mysql_fetch_assoc($result))
{
    if (!$header_done)
    {
        echo "<tr>";
        foreach ($rs as $k=>$v)
        {
            echo "<td>" . htmlspecialchars ($k) . "</td>";
        }
        $header_done = true;
        echo "</tr>";
    }

    // etc...

}

update: here's a function I wrote a few years ago that I use sometimes

function EZ_TBL ( $all_rows, $first_row_headers=TRUE )
{

$tr = array ();

if ( $first_row_headers )
{  
    $td = array ();
    foreach ( $all_rows[0] as $k=>$v )
    {  
        if ( $k == 'sort_order' ) continue;
        $td[] = strtoupper ( $k ); 
    }  

    $tr[] = '<td class="header_row">' . implode ( '</td><td class="header_row">', $td ) . '</td>';
}  

usort ( $all_rows, 'sort_by_sort_order' ); 

foreach ( $all_rows as $row )
{  
    $td = array ();
    foreach ( $row as $k=>$v )
    {  
        if ( $k == 'sort_order' ) continue;

        if ( $k == 'url' )
        {  
            $td[] = '<a href="' . $v . '">' . $v . '</a>';  
        } else {
            $td[] = $v; 
        }  
    }  
    $tr[] = '<td>' . implode ( "</td>\n<td>", $td ) . '</td>';
}  

return '<table><tr>' . implode ( "</tr>\n<tr>", $tr ) . '</tr></table>';
}
网友答案:

You can generate your table header using mysql_list_fields()

EDIT: The function is deprecated, but it does show an example on how to do it by issuing a query.

相关阅读:
Top