显示从mysql表中检索到的下拉列表中的正确值
问题描述:
I have a dropdown list which should be displaying the correct value of the record retrieved from mysql table. Below is what I have tried so far:
<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>
But it's not displaying the correct value. Can someone help me figure out what went wrong here? Thanks.
答
<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>
答
Update: The answer provided by criptic is better - the presence of the selected attribute seems to be enough to select an option in some browsers - see the answers to this question for more detail.
You're using the selected
attribute of the option tag incorrectly:
<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>