mysqli_fetch_field不返回第一个列名

时间:2018-05-11 17:51:34

标签: php

我使用mysqli_fetch_fieldwhile循环中自动填充标题名称。我收到了标题,但它始终缺少第一个标题。我正在使用mysqli_fetch_row并获取表数据的正确列数。

function tableQuery($sql){
    $query = mysqli_query($conn, $sql);
    $columns = 0;

    $tableInfo = mysqli_fetch_field($query);
    echo "<center><h1>Results for " . $tableInfo->table . "</h1></center>";

    echo "<table>";
    echo "<tr>";
        while($headers = mysqli_fetch_field($query)) {
            echo "<th>" . $headers->name . "</th>";
            $columns++;
        }
    echo "</tr>";

        while($row = mysqli_fetch_row($query)) {
            echo "<tr>";
                for ($n = 0; $n <= $columns; $n++) {
                    echo "<td>" . $row[$n] . "</td>";
                }
            echo "</tr>";
        }
    echo "</table>";
}

如果我通过$sql = "SELECT id, name, date FROM users"我的输出如下:

name |   date
______________________________
1    |  Michael  |  1/1/2018
______________________________
2    |    Jack   |  2/5/2018
______________________________
3    |    David  |  4/15/2018

例如,它错过了id表头。 当我var_dump($headers->name)时,我看不到id

3 个答案:

答案 0 :(得分:0)

谢谢 @cdhowie ,问题是我在$tableInfo中获取列名称,因此要么删除表格信息,要么这样做:

function tableQuery($sql){
    $query = mysqli_query($conn, $sql);
    $columns = 0;
    $headerSet = false;

    echo "<table>";
    echo "<tr>";
        while($headers = mysqli_fetch_field($query)) {
            if(!$headerSet){
                echo "<h1> Results for " . $headers->name . "</h1>";
                headerSet = true;
            }
            echo "<th>" . $headers->name . "</th>";
            $columns++;
        }
    echo "</tr>";

        while($row = mysqli_fetch_row($query)) {
            echo "<tr>";
                for ($n = 0; $n <= $columns; $n++) {
                    echo "<td>" . $row[$n] . "</td>";
                }
            echo "</tr>";
        }
    echo "</table>";
}

答案 1 :(得分:0)

替换:

while($headers = mysqli_fetch_field($query)) {
    echo "<th>" . $headers->name . "</th>";
    $columns++;
}

使用:

do {
    echo "<th>" . $tableInfo->name . "</th>";
    $columns++;
} while($tableInfo = mysqli_fetch_field($query))

答案 2 :(得分:0)

你需要的是将指针设置回0(完成查询后)

mysqli_field_seek($ query,0);

...  
mysqli_field_seek($query,0);

echo "<table>";
echo "<tr>";
    while($headers = mysqli_fetch_field($query)) {
        echo "<th>" . $headers->name . "</th>";
        $columns++;
    }
echo "</tr>";
...