Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

List Enum values in dropdown php mysql

Tags:

php

enums

mysql

I have a mysql table which contains following cols.

 Id     Name      Sex

and sex column have type of enum('Male','Female','Unspecified')

How can i list enum values in a dropdown and make current stored value as selected

like image 485
Saqueib Avatar asked Nov 18 '10 03:11

Saqueib


2 Answers

Check this link...its pretty awesome..the script is reusable for any enum column:

http://jadendreamer.wordpress.com/2011/03/16/php-tutorial-put-mysql-enum-values-into-drop-down-select-box/

like image 105
Kavin Mehta Avatar answered Nov 01 '22 09:11

Kavin Mehta


The fact that it is an enum field doesn't matter much when creating the select (dropdown) fields. Enum fields behave the same as a text input field, they just reject any data that doesn't match an enum option and store the data more efficiently. Thus, interacting with an enum field is the same as interacting with a text input field.

So you will need a normal html select field:

<form>
  <select name="gender">
    <option value="Unspecified">Unspecified</option>
    <option value="Male">Male</option>
    <option value="Female">Female</option
  </select>
</form>

And you will need to select your value:

<form>
  <select name="gender">
    <option value="Unspecified" <?php if($gender == "Unspecified") { echo "SELECTED"; } ?>>Unspecified</option>
    <option value="Male" <?php if($gender == "Male") { echo "SELECTED"; } ?>>Male</option>
    <option value="Female" <?php if($gender == "Female") { echo "SELECTED"; } ?>>Female</option
  </select>
</form>

This can be broken out into functions:

function gender_select($default_value='') {
  $select = '<select name="gender">';
  $options = array('Unspecified','Male','Female',);
  foreach($options as $option) {
    $select .= write_option($option, $option, $default_value);
  }
  $select .= '</select>';
  return $select;  
}

function write_option($value, $display, $default_value='') {
  $option = '<option value="'.$value.'"';
  $option .= ($default_value == $value) ? ' SELECTED' : '';
  $option .= '>'.$display.'</option>';
  return $option;
}

So your final code would be:

<form>
<?php echo $gender_select($gender); ?>
</form>
like image 38
Ted Avatar answered Nov 01 '22 11:11

Ted