MySQL Tutorial: Put table column schema enum values in an array

Leave a comment Standard

I hate hard coding enums so you can use this script to get the enum values directly from the table schema. That way if you add or change them you don’t have to go update all of your hard coded nonsense.

$table = "your_table_name";
$field = "field_in_your_tablename";
$sql = "SHOW COLUMNS FROM {$table}";
 
 $result = mysql_query($sql)
 or die (mysql_error());
 
 while ($row = mysql_fetch_row($result))
 {
     if ($row['Field'] == $field)
           $values = $row['Type'];
 }
 
 //remove the formatting around the values
 $enum_array = explode("','", substr($values, 6, strlen($values)-8));
 
 //here are the enum items on your table
 print_r($enum_array);
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s