Display all field (column) names of a table in MySQL database

Posted by Shek on November 23, 2008 under PHP | Be the First to Comment | Total View: 19,763 views

Editor’s note: I mentioned in my previous post Display data from MySQL with PHP which I demonstrated how to display the data of a row within a table, now I want to demonstrate how to display all field names (column names) of a table within a MySQL database.

In order to do so, we have to use 2 PHP functions which are mysql_num_fields() and mysql_field_name().

For mysql_num_fields(), please visit Find the number of column (field) of a table in MySQL database for more details on how it works.

Here I have created a PHP file named “printfieldname.php”:

First we have to connect to the MySQL database:

mysql_connect("Host Name", "User Name", "User Password") or die("Connection Failed");
mysql_select_db("DataBase Name")or die("Connection Failed");

We now create a query to select all records from a table which we would like to print out the column names from and we store the query in a variable:

$query = "select * from tablename";

We then run the query and stored the result in a variable:

$result = mysql_query($query);

Now we use the PHP function mysql_num_fields() to find out the number of column which the table has and we use a variable to store the result:

$numcolumn = mysql_num_fields($result);

We have the number of column now, we then use PHP function mysql_field_name() to find out the column names and to print them out, and to do so, we have to use a for-loop to print out one by one:

We now have to create a for-loop with a counter $i to start at 0 and with a condition to stop when the counter reaches $numcolumn – 1 which equals to the last column’s index, we are going to print out all the column name one by one until the end of the table (the last column):

for ( $i = 0; $i < $numcolumn; $i++ ) {

We then use the function mysql_field_name() to find out the name of the current column which the loop is doing and store it into a variable, the function mysql_field_name() takes two attribute: mysql_field_name(“the result of a query”, “the index of the column: 0 is the first one”), in this case we put $result and $i into it respectively:

$columnnames = mysql_field_name($result, $i);

Now we print out the name by using echo:

echo $columnnames;

We close the for-loop:

 }

So all together, the codes of “printfieldname.php”:

1
2
3
4
5
6
7
8
9
10
11
<?php
mysql_connect("Host Name", "User Name", "User Password") or die("Connection Failed");
mysql_select_db("DataBase Name")or die("Connection Failed");
$query = "select * from tablename";
$result = mysql_query($query);
$numcolumn = mysql_num_fields($result);
for ( $i = 0; $i < $numcolumn; $i++ ) {
$columnnames = mysql_field_name($result, $i);
echo $columnnames;
}
?>

Not what you want? Try a Search

Add A Comment

*