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
开发者_StackOverflow社区
Ideas? :)
$result = mysql_query("SHOW COLUMNS FROM sometable");
print_r($result);
Use
DESCRIBE TableName
or
SHOW COLUMNS FROM TableName
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') );
精彩评论