max0005
max0005

Reputation: 210

PHP get MySQL Columns

I need to build a PHP class which allows me to retrieve the names of all columns of a certain MySQL Database.

Suppose I had the following strucutre:

| ID | Name | Surname | Age | Sex |

My script should provide an array as:

0 => ID
1 => Name
2 => Surname
3 => Age
4 => Sex

Ideas? :)

Upvotes: 1

Views: 118

Answers (3)

Caner
Caner

Reputation: 59308

$result = mysql_query("SHOW COLUMNS FROM sometable");
print_r($result);

Upvotes: 4

VolkerK
VolkerK

Reputation: 96189

You can use the INFORMATION_SCHEMA COLUMNS table, e.g. (using PDO) :

$stmt = $pdo->prepare('
    SELECT
        COLUMN_NAME, DATA_TYPE, IS_NULLABLE, COLUMN_DEFAULT
    FROM
        INFORMATION_SCHEMA.COLUMNS
    WHERE
        table_name=:tablename
        AND table_schema=:databasename
');
$stmt->execute( array(':tablename'=>'foo', ':databasename'=>'bar') );

Upvotes: 1

Luchian Grigore
Luchian Grigore

Reputation: 258648

Use

DESCRIBE TableName

or

SHOW COLUMNS FROM TableName

Upvotes: 3

Related Questions