PHP - 如何打印出我的数据库表?

时间:2016-05-30 11:03:08

标签: php mysql sql

我有一个PHP代码来打印我的表,包括它的列名。打印必须是动态的,因为它必须根据用户输入打印不同的大小/长度表。 :

<table>
    <?php
    while ($row = mysqli_fetch_array($results)) {
        while ($fieldInfo = mysqli_fetch_field($results)) { ?>
            <th> <?php echo $fieldInfo->name; ?> </th>
            <td> <?php echo $row[$fieldInfo->name] ?> </td>
        <?php } 
    } ?>
</table>

这是$results的查询:

$tName = $_POST["tableNames"];   //this data is recieved from another page
require_once("conn.php");
$sql = "SELECT * FROM $tName";
$results = mysqli_query($conn, $sql)
or die ('Problem with query' . mysqli_error($conn));

我的代码正确地打印出表名和第一行数据但是格式不正确这里是它的样子: 另外。由于某种原因,它只打印出第一行,即使我正在使用while循环。

4 个答案:

答案 0 :(得分:0)

使用

mysqli_fetch_field()函数将结果集中的下一列作为对象返回。它只返回所有列名而不是表的记录。

您需要使用mysqli_fetch_array()来获取所有记录:

while ($info = mysqli_fetch_array($results,MYSQLI_ASSOC)) {
  {
  echo $info['rid'];
  echo $info['level'];
  ....
  }

答案 1 :(得分:0)

我给你的建议是准备两个阵列: 第一个:包含列名,第二个:包含数据。

当使用两个foreach生成带标题的第一行和第二个用于显示数据时。您忘记添加<tr>标记来划分行。

答案 2 :(得分:0)

我最终使用了taras'建议将列名存储在数组中:

<table>
    <?php
    while ($fieldInfo = mysqli_fetch_field($results)) { ?>
        <th> <?php echo $fieldInfo->name; ?> </th>
        <?php 
        $colNames[] = $fieldInfo->name;
        ?>
    <?php } 

    while ($row = mysqli_fetch_array($results)) { ?>
        <tr>
        <?php for ($i=0; $i<sizeof($colNames); $i++) { ?>
            <td><?php echo $row[$colNames[$i]] ?>
        <?php } ?>
        </tr>
    <?php } ?>
</table>

答案 3 :(得分:0)

据我所知,你想显示所有表格及其列吗? 所以你可以格式化如下

$sql = "SHOW TABLES FROM dbname";
$result_tables = mysqli_query($link, $sql);
echo "<table border=1>";
echo "<tr><td>Table name</td><td>Fields name</td></tr>";
while($row = mysqli_fetch_array($result_tables)) {
    echo "<tr>";
    echo "<td>".$row[0]."</td>";

    $sql2 = "SHOW COLUMNS FROM ".$row[0];\\row[0] is used to get table name
    $result_fields = mysqli_query($link, $sql2);
    echo "<td>";
    while($row2 = mysqli_fetch_array($result_fields)) {
        echo $row2['Field'].',';
    }
    echo "</td>";
    echo "</tr>";

}
相关问题