418

Is there a way to grab the columns name of a table in MySQL using PHP?

An employee
  • 6,188
  • 9
  • 33
  • 43

19 Answers19

747

You can use DESCRIBE:

DESCRIBE my_table;

Or in newer versions you can use INFORMATION_SCHEMA:

SELECT COLUMN_NAME
  FROM INFORMATION_SCHEMA.COLUMNS
  WHERE TABLE_SCHEMA = 'my_database' AND TABLE_NAME = 'my_table';

Or you can use SHOW COLUMNS:

SHOW COLUMNS FROM my_table;

Or to get column names with comma in a line:

SELECT group_concat(COLUMN_NAME)
  FROM INFORMATION_SCHEMA.COLUMNS
  WHERE TABLE_SCHEMA = 'my_database' AND TABLE_NAME = 'my_table';
SBotirov
  • 13,872
  • 7
  • 59
  • 81
Greg
  • 316,276
  • 54
  • 369
  • 333
  • 26
    DESCRIBE is actually a shortcut for SHOW COLUMNS (http://dev.mysql.com/doc/refman/5.0/en/describe.html) – svens Oct 06 '09 at 16:45
  • @svens yeah, DESCRIBES is simpler, SHOW COLUMNS gives you more options – Greg Oct 06 '09 at 16:47
  • 11
    I would vote for the Information_Schema version, since this syntax is supported by most major databases. Best to only learn 1 way if you have to. – Kibbee Oct 07 '09 at 01:49
  • 4
    +1 I wanted to select table names where a column exist I did `SELECT TABLE_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = 'db_name' AND COLUMN_NAME = 'col_name';` – AL̲̳I May 22 '14 at 10:01
  • @Kibbee, really? I thought "INFORMATION_SCHEMA" was a MySQL proprietary asset? So it is a SQL standard that all database systems implement? – datasn.io Oct 19 '14 at 04:27
  • 2
    save bytes by using `desc my_table;` :-) – Alfonso Embid-Desmet Jan 28 '15 at 18:10
  • @Greg, Why choose `describe` instead of `desc`? – Pacerier May 10 '15 at 07:48
  • down-voted by mistake ... can you please do any update to be able to undo it ... it is really very useful – Amr Bedair Aug 10 '16 at 15:14
  • 5
    `DESC` for describe can be easily confused with `DESC` for descending. The nominal amount of bytes you save for the lack of readability is not worth it. – Jacques Mathieu Jun 22 '17 at 14:46
  • `Error Code: 1054 Unknown column 'businesses' in 'where clause'` – Green Oct 17 '17 at 06:45
46

The following SQL statements are nearly equivalent:

SELECT COLUMN_NAME
  FROM INFORMATION_SCHEMA.COLUMNS
 WHERE table_name = 'tbl_name'
  [AND table_schema = 'db_name']
  [AND column_name LIKE 'wild']

SHOW COLUMNS
FROM tbl_name
[FROM db_name]
[LIKE 'wild']

Reference: INFORMATION_SCHEMA COLUMNS

OMG Ponies
  • 325,700
  • 82
  • 523
  • 502
21

I made a PDO function which returns all the column names in an simple array.

public function getColumnNames($table){
    $sql = "SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE table_name = :table";
    try {
        $core = Core::getInstance();
        $stmt = $core->dbh->prepare($sql);
        $stmt->bindValue(':table', $table, PDO::PARAM_STR);
        $stmt->execute();
        $output = array();
        while($row = $stmt->fetch(PDO::FETCH_ASSOC)){
            $output[] = $row['COLUMN_NAME'];                
        }
        return $output; 
    }

    catch(PDOException $pe) {
        trigger_error('Could not connect to MySQL database. ' . $pe->getMessage() , E_USER_ERROR);
    }
}

The output will be an array:

Array (
[0] => id
[1] => name
[2] => email
[3] => shoe_size
[4] => likes
... )

Sorry for the necro but I like my function ;)

P.S. I have not included the class Core but you can use your own class.. D.S.

Philip
  • 283
  • 3
  • 6
8

There's also this if you prefer:

mysql_query('SHOW COLUMNS FROM tableName'); 
James Goodwin
  • 7,360
  • 5
  • 29
  • 41
7

This solution is from command line mysql

mysql>USE information_schema;

In below query just change <--DATABASE_NAME--> to your database and <--TABLENAME--> to your table name where you just want Field values of DESCRIBE statement

mysql> SELECT COLUMN_NAME FROM COLUMNS WHERE TABLE_SCHEMA = '<--DATABASE_NAME-->' AND   TABLE_NAME='<--TABLENAME-->';
leela
  • 555
  • 4
  • 11
5

It's also interesting to note that you can use
EXPLAIN table_name which is synonymous with DESCRIBE table_name and SHOW COLUMNS FROM table_name although EXPLAIN is more commonly used to obtain information about the query execution plan.

AnthonyS
  • 2,429
  • 2
  • 24
  • 17
5

I needed column names as a flat array, while the other answers returned associative arrays, so I used:

$con = mysqli_connect('localhost',$db_user,$db_pw,$db_name);
$table = 'people';

/**
* Get the column names for a mysql table
**/

function get_column_names($con, $table) {
  $sql = 'DESCRIBE '.$table;
  $result = mysqli_query($con, $sql);

  $rows = array();
  while($row = mysqli_fetch_assoc($result)) {
    $rows[] = $row['Field'];
  }

  return $rows;
}

$col_names = function get_column_names($con, $table);

$col_names now equals:

(
    [0] => name
    [1] => parent
    [2] => number
    [3] => chart_id
    [4] => type
    [5] => id
)
duhaime
  • 25,611
  • 17
  • 169
  • 224
4

Look into:

mysql_query('DESCRIBE '.$table);
Andy Hume
  • 40,474
  • 10
  • 47
  • 58
4

How about this:

SELECT @cCommand := GROUP_CONCAT( COLUMN_NAME ORDER BY column_name SEPARATOR ',\n')
FROM INFORMATION_SCHEMA.COLUMNS 
WHERE TABLE_SCHEMA = 'my_database' AND TABLE_NAME = 'my_table';

SET @cCommand = CONCAT( 'SELECT ', @cCommand, ' from my_database.my_table;');
PREPARE xCommand from @cCommand;
EXECUTE xCommand;
Wolf Metzner
  • 83
  • 1
  • 2
  • 8
3

The MySQL function describe table should get you where you want to go (put your table name in for "table"). You'll have to parse the output some, but it's pretty easy. As I recall, if you execute that query, the PHP query result accessing functions that would normally give you a key-value pair will have the column names as the keys. But it's been a while since I used PHP so don't hold me to that. :)

dannysauer
  • 3,793
  • 1
  • 23
  • 30
  • There are some pretty good docs at php.net within http://us3.php.net/manual/en/function.mysql-list-fields.php – dannysauer Oct 06 '09 at 16:40
3

The mysql_list_fields function might interest you ; but, as the manual states :

This function is deprecated. It is preferable to use mysql_query() to issue a SQL SHOW COLUMNS FROM table [LIKE 'name'] statement instead.

Pascal MARTIN
  • 395,085
  • 80
  • 655
  • 663
  • How does the function work if it doesn't issue a SQL query to the server? Why is it being deprecated? – Pacerier Feb 17 '15 at 07:30
3

You may also want to check out mysql_fetch_array(), as in:

$rs = mysql_query($sql);
while ($row = mysql_fetch_array($rs)) {
//$row[0] = 'First Field';
//$row['first_field'] = 'First Field';
}
thewebguy
  • 1,510
  • 10
  • 15
3

in mysql to get columns details and table structure by following keywords or queries

1.DESC table_name

2.DESCRIBE table_name

3.SHOW COLUMNS FROM table_name

4.SHOW create table table_name;

5.EXPLAIN table_name

denny
  • 2,084
  • 2
  • 15
  • 19
2

you can get the entire table structure using following simple command.

DESC TableName

or you can use following query.

SHOW COLUMNS FROM TableName
2
$col = $db->query("SHOW COLUMNS FROM category");

while ($fildss = $col->fetch_array())
{             
    $filds[] = '"{'.$fildss['Field'].'}"';
    $values[] = '$rows->'.$fildss['Field'].'';
}

if($type == 'value')
{
    return $values = implode(',', $values);
}
else {
     return $filds = implode(',', $filds);
}
Panda
  • 6,955
  • 6
  • 40
  • 55
ibRQD
  • 21
  • 1
  • 1
    To be more helpful to future users could you please provide some context for your answer, not just a code dump. – Paul Zahra Mar 27 '17 at 15:45
1

this worked for me..

$sql = "desc MyTableName";
$result = @mysql_query($sql);
while($row = @mysql_fetch_array($result)){
    echo $row[0]."<br>";
}
Ad Kahn
  • 551
  • 4
  • 6
1

mysqli fetch_field() worked for me:

if ($result = $mysqli -> query($sql)) {
  // Get field information for all fields
  while ($fieldinfo = $result -> fetch_field()) {
    printf("Name: %s\n", $fieldinfo -> name);
    printf("Table: %s\n", $fieldinfo -> table);
    printf("Max. Len: %d\n", $fieldinfo -> max_length);
  }
  $result -> free_result();
}

Source: https://www.w3schools.com/pHP/func_mysqli_fetch_field.asp

David M
  • 193
  • 2
  • 9
1

The easy way, if loading results using assoc is to do this:

$sql = "SELECT p.* FROM (SELECT 1) as dummy LEFT JOIN `product_table` p on null";
$q = $this->db->query($sql);
$column_names = array_keys($q->row);

This you load a single result using this query, you get an array with the table column names as keys and null as value. E.g.

Array(
'product_id' => null,
'sku' => null,
'price' => null,
...
)

after which you can easily get the table column names using the php function array_keys($result)

thundorstorm
  • 99
  • 1
  • 2
0

I have write a simple php script to fetch table columns through PHP: Show_table_columns.php

<?php
$db = 'Database'; //Database name
$host = 'Database_host'; //Hostname or Server ip
$user = 'USER'; //Database user
$pass = 'Password'; //Database user password
$con = mysql_connect($host, $user, $pass);
if ($con) {
    $link = mysql_select_db($db) or die("no database") . mysql_error();
    $count = 0;
    if ($link) {
        $sql = "
            SELECT column_name
            FROM   information_schema.columns
            WHERE  table_schema = '$db'
                   AND table_name = 'table_name'"; // Change the table_name your own table name
        $result = mysql_query($sql, $con);
        if (mysql_query($sql, $con)) {
            echo $sql . "<br> <br>";
            while ($row = mysql_fetch_row($result)) {
                echo "COLUMN " . ++$count . ": {$row[0]}<br>";
                $table_name = $row[0];
            }
            echo "<br>Total No. of COLUMNS: " . $count;
        } else {
            echo "Error in query.";
        }
    } else {
        echo "Database not found.";
    }
} else {
    echo "Connection Failed.";
}
?>

Enjoy!

quantme
  • 3,609
  • 4
  • 34
  • 49
Hussnain sheikh
  • 321
  • 6
  • 9