To get the table and field information of a table in MySQL using PHP we will follow the steps given below:
- Make a connection.
- Select a database.
- Find the number of fields using the mysql_num_fields().
- Then we will print the type, name, length, flags of the field using loop.
For Example:
Suppose we have a database test having the table ex1 which contains columns id(int(11),primary key, auto-increment) and name(string(250)). To display the table and field information yo will write the following script;
<?php
mysql_connect("localhost", "root", "root");
mysql_select_db("test");
$result = mysql_query("SELECT * FROM ex1");
$fields = mysql_num_fields($result);
$rows = mysql_num_rows($result);
$table = mysql_field_table($result, 0);
echo "Your '".$table."' table has ".$fields." fields and ".$rows." record(s)</br>";
echo "The table has the following fields:</br>";
for ($i=0; $i < $fields; $i++ ) {
$type = mysql_field_type($result, $i);
$name = mysql_field_name($result, $i);
$len = mysql_field_len($result, $i);
$flags = mysql_field_flags($result, $i);
echo $type." ".$name." ".$len." ".$flags."</br>";
}
mysql_free_result($result);
mysql_close();
?>
Output of the above code is as follows:
Your 'ex1' table has 2 fields and 4 record(s)
The table has the following fields:
int id 11 not_null primary_key auto_increment
string name 250 not_null
0 Comment(s)