Untitled UI logotext
Solutions
WebsitesEcommerceMobile AppsWeb AppsProduction Support & Maintenance
Our work
Company
About usBlogPodcastContact us
Book a free consultation

Looping through Mysql Columns

Olivia Rhye

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.

Ready to start a project?

Book a free consultation
Untitled UI logotext
Our work
About us
Blog
Careers
Submit a ticket
Agency Partnerships
Contact
© 2024 fjorge. All rights reserved.
Privacy