MySQL数据库表格转换为HTML表格 [英] MySQL database table to HTML table
问题描述
这里$ table的值将从另一个文件传递,它将成为数据库中的表名。
Here the value of $table will be passed from another file and it will be a table name in a database.
使用该表名($ table)am试图获取它的列名和表中的所有值,并使表看起来像我们在phpMyAdmin中看到的实际表。
With that table name ($table) am trying to fetch its column names and all the values in the table and make the table look like an actual one we see in phpMyAdmin.
由于下面的代码。我只能得到列名。但不是数据。请告诉我该怎么做才能完成在表格中显示数据的任务
As a result of the code below. I can only get the column names. But not the data. Please tell me what should i do to perform the task of showing the datas in the table
<table cellpadding="0" cellspacing="0" border="0" width="100%" class="display" rel="datatable">
<thead>
<tr>
<?php
//echo"select * from $table";
$qq=mysql_query("show columns from $table");
if(mysql_num_rows($qq)>0){
//$i=1;
echo '<tr>';
while($rs = mysql_fetch_row($qq))
{
$sel=mysql_query("select * from $table");
$fetch=mysql_fetch_object($sel);
//while($fetch=mysql_fetch_object($sel))
//{
?>
<td><?php echo $fetch->$rs[0];?></td>
<?php
//}
//$i++;
}
echo '</tr>';
}
else
{
?>
<tr>
<td colspan="11">No data to display</td>
</tr>
<?php
}
?>
</tbody>
</table>
推荐答案
我coudn't修复您的代码,因为它得到丑,所以我重拍它:
I coudn't fix your code because it was getting ugly, so i remade it:
php:
php:
function mysql_fetch_all($res) {
$result = array();
while ($row = mysql_fetch_row($res)) {
$result[] = $row;
}
return $result;
}
function getColumnsAndData($table) {
$table = mysql_real_escape_string($table);
$q1 = mysql_query("show columns from $table");
$q2 = mysql_query("select * from $table");
return array(mysql_fetch_all($q1), mysql_fetch_all($q2));
}
list($columns, $data) = getColumnsAndData($table);
?>
html
html
<table cellpadding="0" cellspacing="0" border="0" width="100%" class="display" rel="datatable">
<thead>
<tr>
<?php foreach ($columns as $column): ?>
<td><?php echo $column[0] . ' ' . $column[1] ?></td>
<?php endforeach; ?>
<tr>
</thead>
<tbody>
<?php if (count($data) > 0): ?>
<?php foreach ($data as $row): ?>
<tr>
<?php foreach ($row as $value): ?>
<td><?php echo $value ?></td>
<?php endforeach; ?>
<tr>
<?php endforeach; ?>
<?php else: ?>
<tr>
<td>No data to display</td>
</tr>
<?php endif; ?>
</tbody>
</table>
这篇关于MySQL数据库表格转换为HTML表格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!