2014-01-07 72 views
0

我試圖讓用戶點擊提交時保持其選定值的下拉菜單,但由於表單上的錯誤而失敗。在while循環中查找以前選擇的選項

我有一個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

$地區是什麼? –

+1

您不能使用單引號並期望獲取變量值,您應該使用雙引號。 – ahmad

+0

$ district是所選選項存儲的變量。 – Mike

回答

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>"; 
} 
?> 
0

試試這個..

if($district == $row["name"]) 
{ 
echo "<option value='$district' selected>$district</option>"; 
} 
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"]}"'; 

這是造成問題的原因。