List Enum values in dropdown php mysql

匿名 (未验证) 提交于 2019-12-03 08:46:08

问题:

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

回答1:

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/



回答2:

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>


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!