我想创建一个下拉列表,允许用户选择从数据库中提取的值。根据所选值更新页面时,选择将恢复为“原始”默认选项。如何在页面更新时允许所选值保存并保留?
// Drop Down Menu to choose Session
if (isset($_POST['action']))
{
$action = $_POST['action'];
$session = $_POST['session'];
}
else
{
$action = "";
if (!isset($_POST['session']))
{
$session = "";
}
else
{
$session = $_POST['session'];
}
}
?>
<form name='update' action='emailinquiry_webinarnew.php' method='POST'>
Session:
<select name='session'>
<?php
$query = "SELECT distinct session FROM web_attendees";
$result = mysql_query($query) or die(mysql_error());
while ($row = mysql_fetch_assoc($result))
{
echo "<option>".$row['session']."</option>";
}
?>
</select>
<input type='submit' name="ViewButton" value='View'/>
</form>
答案 0 :(得分:2)
while ($row = mysql_fetch_assoc($result)) {
if($row['session']==$session){
echo "<option selected='selected' >".$row['session']."</option>";
} else {
echo "<option >".$row['session']."</option>";
}
}
希望它对您有用...
答案 1 :(得分:0)
只需在while循环中添加这样的条件,打印选项以添加默认选择该选项的selected="selected"
:
while ($row = mysql_fetch_assoc($result))
{
$selected = '';
if (isset($_POST['session']) && $row['session'] == $_POST['session'])
$selected = ' selected="selected"';
echo "<option{$selected}>".$row['session']."</option>";
}