tags:

views:

196

answers:

2

I have in my database a coloumn say agent which can have enum values ('G','Y','M') where G= google Y= yahoo M= msn

how should i map the output coming from my function i.e google as G in my code so that database recognise it and saves it??

+2  A: 

I think the easiest way is to get the int representation of the enum value. Enums are numbers in the background, so it's usually easy to cast an enum member to a number and vice versa.

You can write a converter class for the best flexibility. You can process the enum value and generate a string, or get a string and return an enum member. You can do this in a simple if-then-else or switch-case structure.

If you are using .NET (C#), be aware that you can pass any number as a parameter even you specify an enum, so an else or a default branch is a must in case of conversion.

If you are using PHP, here is an example:

 $myEnum = array ("red" => 1,"blue" => 2,"yellow" => 3); 
 $d = $myEnum["red"];

You will get 1 for red, 3 for yellow. If you want to use a string:

$myEnum = array ("Google" => "G","Yahoo" => "Y","MSN" => "M"); 
$d = $myEnum["Google"];
artur02
A: 

You're already using ENUM data types, which are just an integer. Why not (in your DB schema, where you define ENUM), just define ENUM('Google','Yahoo','MSN', ...)? That's what I do -- then, when you're pulling/pushing data, you can just use the literal enum value (PHP will treat it like a string when you grab data from the db, and MySQL will treat the string passed from PHP as the enum type, assuming it's the same).

There's really no reason to use 'G' over 'Google', unless you're really that lazy of a typist. And if you're that lazy, why would you want to put another layer of indirection into your code, unnecessarily?

Edit: Sorry for the tone of the post -- it came off as far more harsh than intended. I just happen to feel pretty strongly against unnecessary indirection.

Travis Leleu