简体   繁体   中英

fetching db column names only, for display in dynamic table using php

in the code below Im searching specific columns from a db table and placing them into a html table, inserting &nbsp for empty db fields to maintain uniformed structure. That part works fine, but Im having trouble figuring out the best way to go about getting the column names that are being searched and dynamically displaying them once at the very top of the html table? If my search changes, the column names displayed on the html table will change with it accordingly. Im fairly new to php/mysql and would appreciate any help guys.

$result = mysql_query('SELECT part, ers, make, model, years, oe, core, inlet, outlet FROM parts LIMIT 3');
echo '<table>';
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
    echo '<tr>';
    foreach ($row as $name => $value) {
        if ( $value == "" ) $value="&nbsp;";
        echo '<td> '.$value.' </td>'; 
    }
    echo '</tr>'; 
}
echo "</table>";

How about something like this:

$result = mysql_query('SELECT part, ers, make, model, years, oe, core, inlet, outlet FROM parts LIMIT 3');
echo '<table>';

$cnt = 0;
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
    if ($cnt == 0) {
        $columns = array_keys($row);
        echo '<tr><th>' . implode('</th><th>', $columns) . '</th></tr>';
    }

    $cnt++;
    echo '<tr>';

    foreach ($row as $name => $value) {
        if ( $value == "" ) $value="&nbsp;";
        echo '<td> '.$value.' </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