Abdullah Salma
Abdullah Salma

Reputation: 570

Selecting table column names then display them

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>';
}

Upvotes: 1

Views: 978

Answers (4)

Linga
Linga

Reputation: 10545

Try this

SELECT COLUMN_NAME FROM INFORMATION_SCHEMA WHERE TABLE_NAME = 'my_table';

You can also use

SHOW COLUMNS FROM my_table;

Upvotes: 2

picios
picios

Reputation: 250

$rows = mysql_query("SHOW COLUMNS FROM table_name");

while($row = mysql_fetch_assoc($rows))
{
   echo $row['Field'];
}

Upvotes: 1

chandresh_cool
chandresh_cool

Reputation: 11830

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";
}

Upvotes: 0

Bart Friederichs
Bart Friederichs

Reputation: 33491

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>';
  }
}

Upvotes: 0

Related Questions