记住选择菜单选项

时间:2010-07-13 05:43:30

标签: php

正如标题所说,我该怎么做?

因此,假设用户将消息留空但选择了正确的主题,我希望在页面刷新后选择该主题

我的代码现在:

if (count($_POST) > 0) {

    if (strlen($_POST['topic']) < 1) 
        $errorMsg = "Please select a topic.";
else if (strlen($_POST['message']) < 1)
    $errorMsg = "You have to enter a message.";

}


$topics = mysql_query("SELECT name FROM topics ORDER BY name ASC");

echo '<option value="-1" selected="selected">(Choose Topic)</option>';
while ($t = mysql_fetch_assoc($topics)) {
    echo '<option value="'.$t['id'].'">'.htmlspecialchars($t['name']).'</option>';
}

1 个答案:

答案 0 :(得分:0)

您已经知道selected="selected"会选择该选项,因此您几乎就在那里。

想一想,在你的循环中:

if ($_POST['topic'] == $t['id']) 
    $selected = ' selected="selected';
else 
    $selected = '';
echo '<option value="'.$t['id'].'"' . $selected.'>'.htmlspecialchars($t['name']).'</option>';