我正在尝试使用PHP显示MySQL表的全部内容。我希望代码完全显示该表,并且该代码应该适用于在数据库中创建的任何表。
我已经尝试过了,但是没有用。
<html>
<table>
<tr>
<th>Col 1</th>
<th>Col 2</th>
<th>Col 3</th>
</tr>
<?php
require "config.php";
$strSQL = "SELECT * FROM MyGuests" or die(mysql_error($db));
$rs = mysqli_query($db, $strSQL);
while($row = mysqli_fetch_array($rs)) {
echo "\t<tr><td>".$row['col1data']."</td>
<td>".$row['col2data']."</td><td>".$row['col3data']."</td></tr>\n";
}
mysqli_close($db);
?>
</table>
</html>
它返回Col 1 Col 2 Col 3。
答案 0 :(得分:2)
您提到
它适用于任何表...
如果要显示所有列而不事先知道列将是什么,则需要遍历它们而不是显式命名它们,例如
while($row = mysqli_fetch_array($rs, MYSQLI_ASSOC)) {
echo "<tr>";
foreach ($row as $col)
echo "<td>".$col."</td>";
}
echo "</tr>";
}
您可能还需要提前获取列名,以便可以创建正确数量的表标题单元格。有关如何操作的建议,请参见https://stackoverflow.com/a/1526722/5947043。