Categories
MySQL PHP

Access Column names in MySQL

I recently needed to create a page that would serve as a light admin page for my configuration table.  Just read in the table and let me edit the values. 

However, the field names serve as lables, and sometimes they don't have all the information needed on now the attribute is used, so I maintain more info in the comment for the field.  (The optional COMMENT is part of the meta data for the field in MySQL.)

So I wanted to capture the field comments into an array so that I could place them beside the edit control for each attribute.

Here's my solution:

1
2
3
4
5
6
7
8
9
10
11
12
13
// -------------------- capture column comments into array ---------------
$tablename = "configuration";
$meta_to_capture = array('Field','Comment');
$result = mysql_query("SHOW FULL COLUMNS FROM $tablename");
$row = mysql_fetch_assoc($result);
while ($row = mysql_fetch_assoc($result)) {
  foreach($row as $var => $value){
    if (in_array($var,$meta_to_capture)) {
      $field_comment[$row['Field']] = $row['Comment'];
    }
  }
}
// -------------------- /capture column comments into array --------------

To access it, simply use the following syntax:

$comment = $field_comment['attribute_name'];