1

I want to select all the column names in specific table. then display them.

I searched and get some results like this one.

SELECT `COLUMN_NAME` 
FROM `INFORMATION_SCHEMA`.`COLUMNS` 
WHERE `TABLE_SCHEMA`='yourdatabasename' 
AND `TABLE_NAME`='yourtablename';

if I query this one, how to fetch them and display them ? when I fetch data of any table I display them accourding to their column name.

like:

$table = mysql_query("SELECT * FROM table_name");

while($fetch = mysql_fetch_assoc($table))
{
  echo $fetch['id'] . ":" . $fetch['fullname'] . '<br>';
}
Abdullah Salma
  • 560
  • 7
  • 20
  • 1
    [Please, don't use `mysql_*` functions](http://stackoverflow.com/q/12859942/1190388) in new code. They are no longer maintained and are [officially deprecated](https://wiki.php.net/rfc/mysql_deprecation). See the red box? Learn about prepared statements instead, and use [tag:PDO] or [tag:MySQLi]. – hjpotter92 Apr 25 '13 at 11:10

4 Answers4

2

Try this

SELECT COLUMN_NAME FROM INFORMATION_SCHEMA WHERE TABLE_NAME = 'my_table';

You can also use

SHOW COLUMNS FROM my_table;
Linga
  • 10,379
  • 10
  • 52
  • 104
1
$rows = mysql_query("SHOW COLUMNS FROM table_name");

while($row = mysql_fetch_assoc($rows))
{
   echo $row['Field'];
}
picios
  • 250
  • 1
  • 6
0

When you mysql_fetch_assoc, you get an array where the keys are the column names:

$table = mysql_query("SELECT * FROM table_name");

while($fetch = mysql_fetch_assoc($table))
{
  foreach ($fetch as $column=>$value) {
      echo $column . ":" . $value . '<br>';
  }
}
Bart Friederichs
  • 33,050
  • 15
  • 95
  • 195
0

Try using this

for($i = 0; $i < mysql_num_fields($table); $i++) {
    $field_info = mysql_fetch_field($table, $i);
    echo "Column name: $field_info->name";
}
chandresh_cool
  • 11,753
  • 3
  • 30
  • 45