我正在尝试获取一个下拉菜单,以在用户单击“提交”时保留其选定的值,但是由于表单上的错误而失败。

我有一个while循环,从数据库返回值以构建下拉菜单的选项,但是如何在正确的选项上回显“ selected”?

正如您在下面看到的,我尝试了if($district == $row["name"]) { echo "selected";},但是它不起作用。

<?php

$result = mysql_query("SELECT dist.name FROM districts AS dist JOIN int_bd AS ibd ON dist.id = ibd.districts_id WHERE banners_id = 6 GROUP BY dist.id ORDER BY dist.id ASC", $connection);
if (!result) {
    die("Database query failed: " . mysql_error());
}

while ($row = mysql_fetch_array($result)) {
    echo '<option value="{$row["name"]}"'; if($district == $row["name"]) { echo "selected";} ; echo '>' . $row["name"] . "</option>";
}
?>




抱歉耽搁了。建议的答案都没有对我有用。还有其他想法吗?

最佳答案

你可以试试这个吗

<?php

$result = mysql_query("SELECT dist.name FROM districts AS dist JOIN int_bd AS ibd ON dist.id = ibd.districts_id WHERE banners_id = 6 GROUP BY dist.id ORDER BY dist.id ASC", $connection);
if (!result) {
    die("Database query failed: " . mysql_error());
}

$district = $_REQUEST['name']; // You need pass the value you have been submitted

while ($row = mysql_fetch_array($result)) {
      $selected ="";
     if(trim($district) == trim($row["name"])) {  $selected = "selected";}

    echo '<option value="{$row["name"]}" '.$selected.' >' . $row["name"] . "</option>";
}
?>

10-04 10:34