如何用PHP从MySQL显示字段名


How to display field name from MySQL with PHP

我正在尝试使用PHP从MySQL查询显示字段名。当我将字段名打印到HTML表中时,我没有得到任何要显示的内容,而且我不确定这是否是我应该如何获取字段名的方式。下面是我的代码:

$i = 0;
while( $i < mysqli_num_fields($result)){
$field_names = mysqli_fetch_fields($result);
echo "<th>$field_names->name</th>";
$i++;}

mysqli_fetch_fields()返回一个对象数组,而不是一个对象。

尝试用以下代码替换上面提到的代码,这应该可以工作:

$fields=mysqli_fetch_fields($result);
foreach ($fields as $field) echo "<th>$field->name</th>";

或者在原始代码中使用函数mysqli_fetch_field()的单数版本

有关mysqli_fetch_fields如何工作的更多信息,请查看官方文档:http://php.net/manual/en/mysqli-result.fetch-fields.php

最好使用mysql_fetch_array()

while( $data = mysql_fetch_array($result))
{
    echo "<th>$data['name']</th>";
}