我有一個選擇下拉列表,我希望有一個基于 SQL 數據的預定義選擇選項。我的sql調用:$sel = 'SELECT threechar_currency_code, currency_name FROM currencies';$RS = doQuery($sel);while($row = fetchAssoc($RS)){ //The else is working, the code in the if() is what i wish to get working/* if ($row['threechar_currency_code'] === $selected_currency){ $currencies[] = array( 'selected' => true, 'currency_code' => $row['threechar_currency_code'], 'currency_name' => $row['currency_name'] );} else { */ $currencies[] = array( 'currency_code' => $row['threechar_currency_code'], 'currency_name' => $row['currency_name'] );// }}我的選擇:<select class="mdb-select md-form" id="currency" name="currency" placeholder="Select currency" value="" required searchable="Search here.."> <option value="none" disabled selected="selected">Currency</option> <?php foreach ($currencies as $c){ echo '<option value="'.$c['currency_code'].'">'.$c['currency_name'].'</option>'; } ?> </select>要說明的是,僅使用 else{} 就可以很好地填充所有內容,我只是希望有一個預選選項(如果它與預選值匹配)。提前致謝
2 回答

互換的青春
TA貢獻1797條經驗 獲得超6個贊
您需要selected在循環中指定該屬性(如果存在)
echo '<option value="'.$c['currency_code'].'" ' . (isset($c['selected']) ? "selected=true" : "") . '> . $c['currency_name']</option>
我還會簡化你的while循環。您每次都需要兩個主要屬性,因此始終創建它們,并且僅在需要時添加選定的屬性,例如
while($row = fetchAssoc($RS)){
$currency = [
'currency_code' => $row['threechar_currency_code'],
'currency_name' => $row['currency_name']
]
if($row['threechar_currency_code'] === $selected_currency) {
$currency['selected'] = true;
}
$currencies[] = $currency;
}
- 2 回答
- 0 關注
- 163 瀏覽
添加回答
舉報
0/150
提交
取消