Find the number of column (field) of a table in MySQL database
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:
- Display all field (column) names of a table in MySQL database
- Display data from MySQL with PHP
- Merging 2 MySQL tables with PHP – update one table’s field with another table’s field data (both table have one common field)
- Create MySQL database table with PHP
- Check how many record in the MySQL database matches the query






