2

我想创建一个下拉列表,允许用户选择从数据库中提取的值。当基于所选值更新页面时,该选项将恢复为“原始”默认选项。当页面更新时,如何允许选择的值保存并保留?

// 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>
4

2 回答 2

2
while ($row = mysql_fetch_assoc($result))  {
    if($row['session']==$session){
        echo "<option selected='selected' >".$row['session']."</option>";
    } else {
        echo "<option >".$row['session']."</option>";
    }
}

希望它对你有用...

于 2012-07-19T19:29:43.997 回答
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>";
}
于 2012-07-19T19:29:58.337 回答