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 が提供する回答の方が優れています。選択された属性が存在するだけで、一部のブラウザーではオプションを選択できるようです。詳細については、この質問に対する回答を参照してください。


selectedoption タグの属性を間違って使用しています:

<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 に答える