1

我有一个下拉列表,它应该显示从 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>

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

4

2 回答 2

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>
于 2013-01-01T14:02:41.827 回答
0

更新: criptic 提供的答案更好 - selected 属性的存在似乎足以在某些浏览器中选择一个选项 -有关更多详细信息,请参阅此问题的答案


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>
于 2013-01-01T14:05:11.437 回答