显示从mysql表中检索到的下拉列表中的正确值

时间:2013-01-01 13:56:07

标签: php html

我有一个下拉列表,它应该显示从mysql表中检索到的记录的正确值。以下是我到目前为止所尝试的内容:

   <strong>Authority Id: *</stong><select name="authid">
   <?php

            $authid = $row['AuthorityId'];
    $selectedId = array(
    5, 6, 7);
    $selection = array(
            5 => "Admin",
            6 => "Employee",
            7 => "Student" );
    foreach($selection as $value){
        $text = $value;
        echo '<option value="'.$selectedId.'" selected="'.$authid.'">'.$text.'</option>';
    }
  ?>
  </select>

但它没有显示正确的值。有人能帮我弄清楚这里出了什么问题吗?感谢。

2 个答案:

答案 0 :(得分:0)

<strong>Authority Id: *</strong><select name="authid">
<?php

$authid = $row['AuthorityId']; // Get $authid from database
$selection = array( // Create Index Of AuthIDs and AuthNames
    5 => "Admin",
    6 => "Employee",
    7 => "Student" );

foreach($selection as $key => $value) // Loop Through $selection, Where $key is AuthID and $value is AuthName
{
    echo '<option value="' . $key . '"'; // Start Menu Item
    if ($authid == $key) // Check If AuthID from $selection equals $authid from database
        echo ' selected="selected"'; // Select The Menu Item If They Match
    echo '>' . $value . '</option>'; // End Menu Item
}
?>
</select>

答案 1 :(得分:0)

更新:criptic提供的answer更好 - 所选属性的存在似乎足以在某些浏览器中选择一个选项 - 请参阅the answers to this question for more detail。< / p>


您错误地使用了选项标记的selected属性:

<strong>Authority Id: *</stong><select name="authid">
<?php
 $authid = $row['AuthorityId'];

 $selectedId = array(5, 6, 7);
 $selection = array(
        5 => "Admin",
        6 => "Employee",
        7 => "Student" );

 foreach($selection as $value){
    $text = $value;
    $selected = '';
    if ($selectedID == $authid) {
        $selected = 'selected';
    }
    echo '<option value="'.$selectedId.'" selected="'.$selected.'">'.$text.'</option>';
 }
?>
</select>