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 using mysql php library. I am looking for a template/example of how to come u
Solution 1:
Here is an example on how to read a MySQL table into a HTML table. And no, it does not look nice.
<!DOCTYPE HTMLPUBLIC"-//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);
?><tableborder="1"><tbody><?$result = mysql_query("SELECT firstname, lastname FROM persons")
ORdie(mysql_error());
while($row = mysql_fetch_assoc($result)) {
echo'<tr><td>' . $row['firstname'] . '</td><td>' . $row['lastname'] . '</td></tr>';
}
?></tbody></table></body></html>
Solution 2:
Something like this if you're just wanting the front-end design.
Solution 3:
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>';
Solution 4:
Solution 5:
Here's a function which takes an mysqli
query result and returns an HTML table with headers and data.
<?phpfunctionmysqli_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($rowas$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 ?!
Post a Comment for "Displaying Query Result In A Html Table In Php"