2013-01-01 82 views
1

我有一個下拉列表,應該顯示從mysql表中檢索到的記錄的正確值。以下是我迄今爲止所嘗試的:在從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> 

但它沒有顯示正確的值。有人能幫我弄清楚這裏出了什麼問題嗎?謝謝。

+0

的輸出是什麼?什麼是錯誤? –

回答

1
<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> 
+0

@bEtTyBarnes,如果你需要再詳述一下,我試着解釋它是如何運作的最好的。 = O) –

1

更新:由criptic提供的answer更好 - 選擇屬性的存在似乎是不夠的,選擇在一些瀏覽器的選項 - 見the answers to this question for more detail


您使用的是選項標籤不正確的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> 
相關問題