Let's say that you have a table with the following structure:
+--------------+----------+------+-----+---------+----------------+ | Field | Type | Null | Key | Default | Extra | +--------------+----------+------+-----+---------+----------------+ | Id | int(11) | NO | PRI | NULL | auto_increment | | Author | char(30) | NO | | | | | Title | char(100)| NO | | | | | Summary | text | YES | | | | | ISBN | char(100)| YES | | | | | Release_year | date | NO | | 0 | | +--------------+----------+------+-----+---------+----------------+
and you want to list the column inside mysql and/or php code.
There are 2 mysql queries you do that: describe `table` and show columns from `table` where `table` must be replace with the name of the table.
Describe `table` provides information about the columns in a table. It is a shortcut for show columns from `table` and it does not have any conditions at all. As of MySQL 5.0.1, these statements also display information for views.
More information about the describe `table` can be found here: http://dev.mysql.com/doc/refman/5.0/en/describe.html.
The full syntax for show columns from `table` is:
SHOW [FULL] COLUMNS {FROM | IN}tbl_name
[{FROM | IN}db_name
] [LIKE 'pattern
' | WHEREexpr
]
Show columns displays information about the columns in a given table. It also works for views as of MySQL 5.0.1. The like clause, when it's present, indicates which column names to match. The where clause can be given to select rows using more general conditions.
For example, if you want to show only the column "release_year" you will use show columns from `table` like 'year.' You can use inside php like this:
$res = myql_query("show columns from `table` like 'year' ") or die(mysql_error());
$row = mysql_fetch_row($result);
preg_match_all('/\'(.*?)\'/', $row[1], $enum_array); if (!empty($enum_array[1]))
{
/* Shift array keys to match original enumerated index in MySQL (allows for use of index values instead of strings) */
foreach($enum_array[1] as $mkey => $mval)
$enum_fields[$mkey+1] = $mval;
return $enum_fields;
}
More information about the show columns from `table` can found http://dev.mysql.com/doc/refman/5.0/en/show-columns.html