如何在不手动指定列的情况下以 HTML 显示所有 DB 列的记录?

我想从 PostgreSQL DB 表中提取所有记录,并使用 HTML 中的表显示这些数据,而不指定列名。我有很多包含很多列的表,所以我希望我的 HTML 查询尽可能地响应。


使用下面的代码,我可以从数据库中查询数据并在浏览器上打印数据,但我必须指定要显示的列。


<!DOCTYPE html>

<html>

<head>

<meta charset=utf-8"> 

<title>Map</title>

</head>


<body onload="init()">

<h1>Map</h1>


<div>

<?php

$conn = pg_connect("host=localhost port=5432 dbname=visualization user=postgres password=*******");

$result = pg_query($conn,"SELECT * FROM myTable");

echo "<table>";

while($row=pg_fetch_assoc($result)){

    echo "<tr>";

    echo "<td width='200'>" . $row['lon'] . "</td>";  // set col manually

    echo "<td width='200'>" . $row['lat'] . "</td>";  // set col manually

    echo "</tr>";

}

echo "</table>";

pg_close($conn);

?>

</div>

</body>

</html>

结果如下:

http://img2.mukewang.com/634901270001cd9503600487.jpg

我只显示 2 列,因为我手动指定了列。我想在不手动指定的情况下显示表中的所有列及其记录(最多 100 列)。如何做到这一点?



翻阅古今
浏览 72回答 3
3回答

SMILET

由于您的列位于数组中,因此您可以foreach()在行上方。列的显示要么需要足够好,要么只保留默认值,以使显示看起来合理......while($row=pg_fetch_assoc($result)){&nbsp; &nbsp; echo "<tr>";&nbsp; &nbsp; foreach ( $row as $key => $value )&nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; echo "<td align='center' width='200'>" . $value . "</td>";&nbsp; &nbsp; }&nbsp; &nbsp; echo "</tr>";}

杨__羊羊

尝试 :while($row=pg_fetch_assoc($result)){&nbsp; &nbsp; echo "<tr>";&nbsp; &nbsp; $maxColumnDisplay = 100;&nbsp; &nbsp; foreach($row as $col){&nbsp; &nbsp; &nbsp; &nbsp; if(!$maxColumnDisplay--) break;&nbsp; &nbsp; &nbsp; &nbsp; echo "<td align='center' width='200'>" . $col . "</td>";&nbsp; &nbsp; }&nbsp; &nbsp; echo "</tr>";}

慕少森

尝试这个:function printTable(&$result) //result set{&nbsp; &nbsp; /**&nbsp; Set up Table and Headers **/&nbsp; &nbsp; $fieldinfo = $result->fetch_fields();&nbsp; &nbsp; echo '<table class="sqldump">' . "\n";&nbsp; &nbsp; echo '<tr class="header">' . "\n";&nbsp; &nbsp; foreach ($fieldinfo as $fieldval) {&nbsp; &nbsp; &nbsp; &nbsp; echo "<td>".$fieldval->name."</td>\n";&nbsp; &nbsp; }&nbsp; &nbsp; echo "</tr>\n";&nbsp; &nbsp; /** dump rows **/&nbsp; &nbsp; while($row = $result->fetch_assoc()) {&nbsp; &nbsp; &nbsp; &nbsp; echo "<tr>";&nbsp; &nbsp; &nbsp; &nbsp; foreach ($row as $column) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; echo "<td>".$column."</td>\n";&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; echo "</tr>";&nbsp; &nbsp; }&nbsp; &nbsp; echo "</table>\n";&nbsp; &nbsp; /**&nbsp; gc&nbsp; **/&nbsp; &nbsp; $result->free();}
打开App,查看更多内容
随时随地看视频慕课网APP