简体   繁体   中英

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.

$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?

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 . 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...

FROM php.net/...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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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