Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to can I get the names of my mysql table columns

Tags:

php

mysql

RESOLVED I have used the answer from alfasin, but as that gave me WAY too much information, i wrote a little script to just get the field names. As the field names apeared first, it was rather simple:

  $here = array();
  $SQL = "SHOW COLUMNS FROM User";
    foreach($conn->query($SQL) as $row) {
      $here[] = $row[0];
    }
  echo '<pre>';print_r($here);echo '<pre>';

This left me with the new array $here containing the column names, hope this helps someone in the future :)


Original question:
Let me clarify a bit, I have a mysql table and I'm trying to select * from it, and display the result in an html list <ol>. I can manage to grab the row data JUST FINE, but I cannot for the life of me figure out how to grab the table column names, in order to match them up with the row, respectively. this is my code that is grabbing the row data:

//get those results
 $sql = "SELECT DISTINCT *
 FROM User
 WHERE Owner = '".$owner."'";
  foreach($conn->query($sql) as $row) {
  //split array in half
  $hax = count($row);
  $halfHax = $hax / 2;
   //set up a for loop to give results
    $u = 1;
      for($i = 2; $i <= $halfHax; $i++){
        echo $row[$u].'<br>';
        $u++;
      }
   }

this is giving me all the result where Owner == $owner just like it should, but I would like the column names to list with those, I could hard-code it out, but more columns may be added/changed so I would rather not. Any ideas?

like image 475
Nick Avatar asked Feb 04 '13 21:02

Nick


People also ask

How can I get all column names in MySQL table?

$query = query("DESC YourTable"); $col_names = array_column($query, 'Field'); That returns a simple array of the column names / variable names in your table or array as strings, which is what I needed to dynamically build MySQL queries.

How do I get a list of column names in a table in SQL?

USE db_name; DESCRIBE table_name; it'll give you column names with the type.

How do I get a list of column names in a table?

We can verify the data in the table using the SELECT query as below. We will be using sys. columns to get the column names in a table. It is a system table and used for maintaining column information.


1 Answers

Try:

SHOW COLUMNS FROM mytable

http://dev.mysql.com/doc/refman/5.0/en/show-columns.html

like image 147
Nir Alfasi Avatar answered Oct 05 '22 22:10

Nir Alfasi