使用 mysqli_fetch_array 和 mysqli_fetch_field 从数据库获取数据

Get data from database with mysqli_fetch_array and mysqli_fetch_field

我想使用 mysqli_fetch_arraymysqli_fetch_field 从我的数据库中查询数据,但它根本不起作用。 我有这样的 tbl_student table:

| id | firstname | lastname |
| -- | --------- | -------- |
| 1  |  first_A  |  last_A  |
| 2  |  first_B  |  last_B  |
| 3  |  first_C  |  last_C  |

PHP代码:

$query = "select * from tbl_student";
$result = mysqli_query($db, $query);
while ($row = mysqli_fetch_array($result)) {
    while ($col = mysqli_fetch_field($result)) {
        echo $col->name . " = " . $row[$col->name];
        echo "<br>";
    }
    echo "<br>";
}

如我所愿,我想要这样的结果:

id = 1
firstname = first_A
lastname = last_A

id = 2
firstname = first_B
lastname = last_B

id = 3
firstname = first_C
lastname = last_C

但是没有,我只有第一条记录:

id = 1
firstname = first_A
lastname = last_A

我该怎么做?

mysqli_fetch_field旨在获取查询中字段的详细信息,而不是获取记录中每个字段的信息。

使用以下代码获得您想要的结果。

while ($row = mysqli_fetch_array($result)) {
    foreach ($row as $key => $value) {
        echo $key . " = " . $value;
        echo "<br>";
    }
    echo "<br>";
}