Forum Moderators: coopster

Message Too Old, No Replies

Generate array of possible ENUM mysql values

         

whoisgregg

8:49 pm on Sep 2, 2006 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Having trouble wrapping my head around this today. :/ I have a field in a mySQL table defined as an ENUM field. I'm writing a pretty GUI for it and want the selection of field values to dynamically match what is in the database. I'm looking to generate an array of all possible values.

So, I start with this:

// $column_definition = $db->query_to_array("SHOW COLUMNS FROM `sp_sizes` LIKE 'category'");
// the line above is how I am actually getting the print_r'd data below, but it won't work without the DB class I use and with an appropriately setup table definition, so here's a handy line to build the relevant part of the array:
$column_definition = array( array("Type"=>"enum('Standard','Discount','Expedited')") );
print_r($column_definition);
/*
[0] => Array
(
[Field] => shiptype
[Type] => enum('Standard','Discount','Expedited')
[Null] => YES
[Key] =>
[Default] =>
[Extra] =>
)
*/

So, I think I turn that Type = enum thing into an array with this:

$shiptype = str_replace( "enum(", '$shiptype_possible_categories = array(', $column_definition[0]['Type']).';';
echo $shiptype;
// $shiptype_possible_categories = array('Standard','Discount','Expedited');
eval($shiptype);
print_r($shiptype_possible_categories);
/*
Array
(
[0] => Standard
[1] => Discount
[2] => Expedited
)
*/

But since this involves using eval, I was hoping someone else could take a look at it. And perhaps someone has a more elegant way of getting the possible enum values out of a mysql table?

Working on the weekend, no wonder I'm having trouble concentrating... :(

coopster

4:15 pm on Sep 7, 2006 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



I wouldn't say using eval() in a case such as this is bad, as a matter of fact it is handy. You are controlling the supplied input because you created the table definition. On the other hand though, a regular expression would work here quite well too:
preg_match_all("/'([^\']*)'/", $column_definition[0]['Type'], $matches); 
$shiptype_possible_categories = $matches[1];
print_r($shiptype_possible_categories);

whoisgregg

4:06 pm on Sep 8, 2006 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Thanks coopster! :)

eval makes me nervous, even when I'm sure it's not a problem.