Looping through Mysql Columns

Andy Stramer

Recently I was looking into a way to echo out each column name of a mysql database. Of course I needed to do it dynamically as the database could change and the application is in PHP.

First the Query:

$col_query = "SHOW COLUMNS FROM `your_tablename`";
$col_res = mysql_query($col_query) or die(mysql_error());

This query result will return an array of the columns. There are a few keys to the array to point out. Field is your column name. Type is the data type. Others include Null, Key, Default, and Extra. So to get the results I’ve been looking for I had to add the following PHP code.

$col_query = "SHOW COLUMNS FROM `your_tablename`";
$col_res = mysql_query($col_query) or die(mysql_error());
 
//Here is what I needed to add
while($col = mysql_fetch_assoc($col_res))
{
     echo $col['Field'];
}

This little snippet of code can make life easier if you are displaying data in a database dynamically.

Last updated by on .

What Are Your Thoughts?

Your email address will not be published. Required fields are marked *