0

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

2 Answers 2

1

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>';
}
Sign up to request clarification or add additional context in comments.

Comments

1

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.

2 Comments

The page you link mentions that mysql_list_fields is deprecated in favor of using mysql_query with a "SQL SHOW COLUMNS" statement
@George Pittarelli Thanks for pointing this out, I've updated my answer. Cheers!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.