[英]Get column information from results of mysql query in php?
I am trying to print out the column headers for any query entered. 我正在尝试打印出输入的任何查询的列标题。 I have other code that connects to the database and actually prints the results, but I am having trouble with the line
我还有其他代码可以连接到数据库并实际打印结果,但是该行遇到了麻烦
'$result .= $heading->name;'
I keep getting this error: 我不断收到此错误:
'Catchable fatal error: Object of class mysqli_result could not be converted to string in...'
Could someone explain what the problem is? 有人可以解释是什么问题吗? According to the php manual this should give me the right information.
根据PHP手册,这应该给我正确的信息。 I am fairly new to php though, so if you improve the code could you please explain how you did it?
我对php还是相当陌生,所以如果您改进了代码,可以请您解释一下它是如何做到的?
I have the following code so far that gets a result from a query: 到目前为止,我有以下代码可从查询中获取结果:
$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
is an object being used by mysqli. $result
是mysqli使用的对象。 Then you try to append a string onto the end of it. 然后尝试在其末尾附加一个字符串。
Just use a different variable name besides $result
which will be a string in which you will collect the names of your columns. 只需使用
$result
以外的其他变量名,该变量名将是一个字符串,您将在其中收集列的名称。 Or you might save the names in an array like this: 或者您可以将名称保存在这样的数组中:
$var[] = $heading->name;
since $result is an object you are using for executing the query, i won't be able to store any other data coming from db. 由于$ result是您用于执行查询的对象,因此我将无法存储来自db的任何其他数据。 you have to take another variable (say $variable ) to store the data coming from db.
您必须使用另一个变量(例如$ variable )来存储来自db的数据。 Follow the below code:
请遵循以下代码:
$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
}
}
}
I hope this will solve the issue.. 我希望这可以解决问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.