Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL query to get column names?

Tags:

php

mysql

I'd like to get all of a mysql table's col names into an array in php?

Is there a query for this?

like image 373
Haroldo Avatar asked Nov 12 '10 13:11

Haroldo


People also ask

How do I get column names in SQL query?

The following query will give the table's column names: SELECT column_name FROM INFORMATION_SCHEMA. COLUMNS. WHERE TABLE_NAME = 'News'

How do I find columns in MySQL?

SELECT table_name, column_name from information_schema. columns WHERE column_name LIKE '%column_name_to_search%'; Remember, don't use % before column_name_to_search if you know the starting characters of that column.

How do I get all columns in MySQL?

The more flexible way to get a list of columns in a table is to use the MySQL SHOW COLUMNS command. As you can see the result of this SHOW COLUMNS command is the same as the result of the DESC statement. For example, the following statement lists all columns of the payments table in the classicmodels database.


1 Answers

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

like image 55
ircmaxell Avatar answered Oct 09 '22 04:10

ircmaxell