List Enum values in dropdown php mysql
I have a mysql table which contains following cols.
Id Name Sex
and sex column have type of 开发者_Go百科enum('Male','Female','Unspecified')
How can i list enum values in a dropdown and make current stored value as selected
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/
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>
精彩评论