Find the number of column (field) of a table in MySQL database

Posted by Shek on November 16, 2008 under PHP | Be the First to Comment | Total View: 753 views

To find and print out the number of column (field) of a table in MySQL database, we have to use a php function “mysql_num_fields()” to get the number and to use a variable to store the result, here I have created an example to demonstrate how to do so:

I have create a PHP file named “shownofield.php” and the codes of it are:

First we have to connect to the database:

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

Then we create a query to select all the records within the table which you want to find out the number of column:

$query = "select * from table";

We run the query here and a variable is created to store the result which matches the condition of the query above:

$result = mysql_query($query);

Now we use the PHP function “mysql_num_fields()” to get the number of column (field) in a table and we create a variable to store the result (Integer):

$numcolumn = mysql_num_fields($result);

At last, we print out the result:

echo $numcolumn;

All together we have for “shownofield.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 table";
$result = mysql_query($query);
$numcolumn = mysql_num_fields($result);	
echo $numcolumn;

Similar Posts:

VN:F [1.9.15_1155]
Rating: 10.0/10 (1 vote cast)
VN:F [1.9.15_1155]
Rating: +1 (from 1 vote)
Find the number of column (field) of a table in MySQL database, 10.0 out of 10 based on 1 rating

Add A Comment

*