我正在尝试使用下拉菜单在用户点击提交时保留其选定的值,但由于表单上的错误而失败。
我有一个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>";
}
?>
抱歉延误。所有建议的答案都不适合我。还有其他想法吗?
答案 0 :(得分:0)
你能试试吗,
<?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>";
}
?>
答案 1 :(得分:0)
试试这个..
if($district == $row["name"])
{
echo "<option value='$district' selected>$district</option>";
}
答案 2 :(得分:0)
我刚刚找到答案。这就是我所做的:
while ($row = mysql_fetch_array($result)) {
echo '<option value="' . $row["name"] . '"';
if($row["name"] == $district) { echo 'selected';} ;
echo '>' . $row["name"] . '</option>';
}
似乎是这一行
echo '<option value="{$row["name"]}"';
导致了这个问题。