I am trying to get the names of the fields (ie the structure of the table) in MySQL. I am using PHP to connect to MySQL.
This is my query:
SELECT `COLUMN_NAME`
FROM `INFORMATION_SCHEMA`.`COLUMNS`
WHERE `TABLE_SCHEMA`='database'
AND `TABLE_NAME`='Job Hunt'
And this is the PHP code:
$sql = "SELECT `COLUMN_NAME` FROM `INFORMATION_SCHEMA`.`COLUMNS` WHERE `TABLE_SCHEMA`='database' AND `TABLE_NAME`='Job Hunt'";
$result = mysqli_query($conn,$sql);
$row = mysqli_fetch_assoc($result);
print_r($row);
The output should read:
Array
(
[COLUMN_NAME] => id
[COLUMN_NAME] => Company Name
[COLUMN_NAME] => Address
[COLUMN_NAME] => Date of Visit
)
When I use the code above, the result only returns one row (or one "column header"):
Array
(
[COLUMN_NAME] => id
)
How do I get an array of all the column names and what am I doing wrong?
You could use this to list down table columns.
SHOW COLUMNS FROM YOURTABLENAME;
OR
DESC YOURTABLENAME
In both the ways you can get your need done, whereas desc results you with associated column attributes as well.
EDIT
SELECT GROUP_CONCAT(
COLUMN_NAME ) FROM
INFORMATION_SCHEMA .
COLUMNS WHERE
TABLE_SCHEMA ='database' AND
TABLE_NAME ='Job Hunt'
USE GROUP_CONCAT
to achieve it, this will group all your column names into one record and in one column.
Find more aggregate functions here, http://dev.mysql.com/doc/refman/5.7/en/group-by-functions.html .
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.