开发者

Displaying query result in a HTML table in PHP

I need to display a table in a web page. The data from the table comes from database which I can query us开发者_C百科ing mysql php library. I am looking for a template/example of how to come up with a nice looking table (I am not good at front end design).

Any link/example/references will be appreciated.


Here is an example on how to read a MySQL table into a HTML table. And no, it does not look nice.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
    <head>
        <title>Read values from MySQL</title>
    </head>
    <body>
        <?
            mysql_connect($db_host,$db_user,$db_pw);
            mysql_select_db($db_name);
        ?>
        <table border="1">
            <tbody>
                <?
                    $result = mysql_query("SELECT firstname, lastname FROM persons")
                        OR die(mysql_error());
                    while($row = mysql_fetch_assoc($result)) {
                        echo '<tr><td>' . $row['firstname'] . '</td><td>' . $row['lastname'] . '</td></tr>';
                    }
                ?>
            </tbody>
        </table>
    </body>
</html>


Assuming your rows are an array of PHP objects...

echo '<table>';
foreach ($rows as $row) {
    echo '    <tr>';
    echo '        <td>'.$row->column_1.'</td>';
    // etc.
    echo '    </tr>';
}
echo '</table>';


Here's a function which takes an mysqli query result and returns an HTML table with headers and data.

<?php
    function mysqli_result_2_table( $query_result, $width = '100%' ) {
        
        $nrows = mysqli_num_rows($query_result);
        
        if( $nrows > 0 ) {
        
            $table = '<table style="width:' . $width . '"><thead><tr style="background-color:#ccc;color:#000;">';
            $nfields = mysqli_num_fields($query_result);
            while( $field = mysqli_fetch_field( $query_result ) ) {     
                $table .= '<th>' . ucfirst($field->name) . '</th>'; 
            }
            $table .= '</tr></thead><tbody>';
            
            $even = true;
            while( $row = mysqli_fetch_assoc($query_result) ) {

                $table .= '<tr style="' . ($even ? 'background-color:#eee' : 'background-color:#ddd') . '">';
                $even = !$even;
                foreach($row as $field => $value) {
                    $table .= '<td>' . $value . '</td>';
                }
                $table .= '</tr>';
            }
            $table .= '</tbody><tfoot><tr style="background-color:#ccc;color:#000"><td colspan="' . $nfields . '">Query returned ' . $nrows . ' records.</td></tr></tfoot></table>';
        }
        else { echo '<p>Query returned an empty result (no rows).</p>'; }

        return $table;
    }

?>

I have modified it quite heavily, but here is the original source for reference: sql query -> html table ?!

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜