print mysql table fields

How to display mysql table fields using PHP

It is common to find the mysql table field names in the given table while creating dynamic models for our web applications.To continue this tutorial we have to create a test table. Below mysql query is used to create this test table.

CREATE TABLE  `testtable` (
  `test_id` INTEGER UNSIGNED NOT NULL AUTO_INCREMENT,
  `test_name` VARCHAR(45) NOT NULL,
  `test_created` DATETIME NOT NULL,
  PRIMARY KEY (`test_id`)
)
ENGINE = InnoDB;

SHOW COLUMNS FROM TABLENAME query is used for list the mysql fields.

below code lists the mysql table fields.

<?php  
//replace it with your host normally it could be localhost
$hostname='localhost';
//mysql user name
$username='username';
//mysql user password
$password='password';
//connect to the mysql server
$ss = mysql_pconnect($hostname, $username, $password) or trigger_error(mysql_error(),E_USER_ERROR); 
//select a database on the mysql server
//please change as you like the database name
mysql_select_db('mydatabase'); 
 
//SHOW COLUMNS FROM TABLENAME
$query=mysql_query('SHOW COLUMNS FROM testtable ') or die(mysql_error());
 
//iterate trough the query result and fetch each field
while($field=mysql_fetch_object($query)){
$fields[]=$field;//collect each field into a array
};
 
print_r($fields);//test the fields array
 
foreach($fields as $key=>$field){
echo $field->Field.'</br>'; // print each field name
}
 
?>

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="" highlight="">