在下拉列表 php mysql 中列出枚举值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4211395/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 12:18:07  来源:igfitidea点击:

List Enum values in dropdown php mysql

phpmysqlenums

提问by Saqueib

I have a mysql table which contains following cols.

我有一个包含以下列的 mysql 表。

 Id     Name      Sex

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

和性别列的类型为 enum('Male','Female','Unspecified')

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

如何在下拉列表中列出枚举值并将当前存储的值设为选定值

回答by Kavin Mehta

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/

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

回答by Ted

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:

所以你需要一个普通的 html 选择字段:

<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>