简体   繁体   English

查询结果为空后如何获取mysql查询的列名

[英]How can I get column names of a mysql query after the query result is empty

I want to generate an array of colnames after performing a query. 我想在执行查询后生成一个colnames数组。

$sql = "SELECT prename, lastname, CONCAT (prename, ' ', lastname AS name) 
       FROM mytable WHERE ... ";
$result = mysqli_query($con,$sql);
$row = mysqli_fetch_assoc($result);
foreach ( $row as $key => $value ) $colNames[] = $key;

I know that I can get the colnames of a table using 我知道我可以使用

$sql = "SHOW COLUMNS FROM mytable;   

But how can I get colnames, that are created using MySql functions like "CONCAT ... " if the query-result is empty? 但是,如果查询结果为空,如何获得使用MySql函数(例如“ CONCAT ...”)创建的名字呢?

Therefore my question: 因此我的问题是:

Is it possible to get the column names of a query that returns an empty result? 是否可以获取返回空结果的查询的列名?

Is it possible to get the column names of a query that returns an empty result? 是否可以获取返回空结果的查询的列名?

No, it is not possible because when you get the results you receive an associative array with keys<=>values . 不,这是不可能的,因为当您获得结果时,您会收到带有keys <=> values的关联数组。 So if you receive an empty result there are no values, and if there are no values, there is no associative array to get the keys from. 因此,如果收到的结果为空,则没有值,如果没有值,则没有关联数组可用于获取键。

If you are trying to write a minimalist block of code, you might want to try another approach. 如果您尝试编写极简代码块,则可能需要尝试另一种方法。 But you all ready wrote the answer: $sql = "SHOW COLUMNS FROM mytable; and it probably takes 0.0001 secs so... 但是大家都准备好了答案: $sql = "SHOW COLUMNS FROM mytable;可能需要0.0001秒,所以...

FROM php.net/...mysql_fetch_assoc() php.net / ... mysql_fetch_assoc()

mysql_fetch_assoc mysql_fetch_assoc
Return Values: 返回值:
Returns an associative array of strings that corresponds to the fetched row, or FALSE if there are no more rows. 返回与提取的行相对应的字符串关联数组 ,如果没有更多行,则返回FALSE

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM