从 php 中的 mysql 查询结果中获取列信息


Get column information from results of mysql query in php?

我正在尝试打印出输入的任何查询的列标题。我有其他代码连接到数据库并实际打印结果,但我在行上遇到问题

'$result .= $heading->name;'

我不断收到此错误:

'Catchable fatal error: Object of class mysqli_result could not be converted to string in...'

有人可以解释问题是什么吗?根据 php 手册,这应该给我正确的信息。不过,我对 php 相当陌生,所以如果你改进代码,你能解释一下你是怎么做到的吗?

到目前为止,我有以下代码可以从查询中获取结果:

$result = mysqli_query($conn,$query);
if($result){
    if( mysqli_num_rows($result)>0){
        $columnNo = mysqli_num_fields($result);
        for($i=0;$i<$columnNo;$i++){
            $heading = mysqli_fetch_field_direct($result,$i);
            $result .= $heading->name;
        }
    }
}

$result是Mysqli使用的对象。然后,您尝试将字符串附加到其末尾。

只需使用除$result之外的其他变量名称,该变量名称将是一个字符串,您将在其中收集列的名称。或者,您可以将名称保存在如下所示的数组中:

$var[] = $heading->name;

由于$result是用于执行查询的对象,因此我将无法存储来自数据库的任何其他数据。 您必须采用另一个变量(例如$variable(来存储来自数据库的数据。按照以下代码操作:

$result = mysqli_query($conn,$query);
$variable='';  // add this
if($result){
    if( mysqli_num_rows($result)>0){
        $columnNo = mysqli_num_fields($result);
        for($i=0;$i<$columnNo;$i++){
            $heading = mysqli_fetch_field_direct($result,$i);
            $variable .= $heading->name;  //modify here
        }
    }
}

我希望这将解决问题。