MySQL query to get column names?

The best way is to use the INFORMATION_SCHEMA metadata virtual database. Specifically the INFORMATION_SCHEMA.COLUMNS table...

SELECT `COLUMN_NAME` 
FROM `INFORMATION_SCHEMA`.`COLUMNS` 
WHERE `TABLE_SCHEMA`='yourdatabasename' 
    AND `TABLE_NAME`='yourtablename';

It's VERY powerful, and can give you TONS of information without need to parse text (Such as column type, whether the column is nullable, max column size, character set, etc)...

Oh, and it's standard SQL (Whereas SHOW ... is a MySQL specific extension)...

For more information about the difference between SHOW... and using the INFORMATION_SCHEMA tables, check out the MySQL Documentation on INFORMATION_SCHEMA in general...


Seems there are 2 ways:

DESCRIBE `tablename`

or

SHOW COLUMNS FROM `tablename`

More on DESCRIBE here: http://dev.mysql.com/doc/refman/5.0/en/describe.html


I have done this in the past.

SELECT column_name
FROM information_schema.columns
WHERE table_name='insert table name here'; 

You can use the following query for MYSQL:

SHOW `columns` FROM `your-table`;

Below is the example code which shows How to implement above syntax in php to list the names of columns:

$sql = "SHOW COLUMNS FROM your-table";
$result = mysqli_query($conn,$sql);
while($row = mysqli_fetch_array($result)){
    echo $row['Field']."<br>";
}

For Details about output of SHOW COLUMNS FROM TABLE visit: MySQL Refrence.

Tags:

Mysql

Php