views:

87

answers:

3

I've tried this: http://be.php.net/manual/en/function.mysql-list-fields.php, but there's too much detail here.

What I'm looking for is a function that returns an array of strings. This array should only contain the names of all columns that a certain table has.

So for instance, if I have a table with these columns:

username | email | gender |age | married | number_of_children | street | province

I should get the same thing as if I did this:

$vars = array('username','email','gender','age','married','number_of_children','street','province');

Is there a PHP function already that can do this? Or shall I need some SQL statements of my own?

+1  A: 

I think there is no direct PHP function that will do what you want.

You can:

  • use that function discarding the unneeded results.
  • use a SQL query over the INFORMATION_SCHEMA

    SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = 'database' AND TABLE_NAME = 'table'

  • use the MySQL specific 'desc table' or 'show columns from table' SQL sentences

Vinko Vrsalovic
+1  A: 

Theres a MySQL Query, which returns the column names asa result set.

SHOW COLUMNS FROM tablename
Dean
+4  A: 

you could also do

$query = mysql_query("SELECT * FROM `table`");
$result = mysql_fetch_assoc($query);
$keys = array_keys($result);

$keys will now contain all of the column names because they were the array keys in the $result array.

contagious
If you only want the column names, you better append a 'limit 0' at the end of that query so you don't bring all the data alongside the column names
Vinko Vrsalovic