简体   繁体   English

如何使用mysql和php获取所有列名

[英]How to get ALL column names using mysql and php

I am trying to get the names of the fields (ie the structure of the table) in MySQL. 我试图在MySQL中获取字段的名称(即表的结构)。 I am using PHP to connect to MySQL. 我正在使用PHP连接到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: 这是PHP代码:

$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. 在这两种方式中,您可以完成需求,而desc也会为您提供相关的列属性。

EDIT 编辑

SELECT GROUP_CONCAT( COLUMN_NAME ) FROM INFORMATION_SCHEMA . SELECT GROUP_CONCAT( COLUMN_NAME ) FROM INFORMATION_SCHEMA . COLUMNS WHERE TABLE_SCHEMA ='database' AND TABLE_NAME ='Job Hunt' 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. 使用GROUP_CONCAT来实现它,这会将您的所有列名称分组到一个记录和一列中。

Find more aggregate functions here, http://dev.mysql.com/doc/refman/5.7/en/group-by-functions.html . 在这里找到更多聚合函数, http://dev.mysql.com/doc/refman/5.7/en/group-by-functions.html

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

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