我有一个选择下拉列表,我希望有一个基于 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 关注
- 100 浏览
添加回答
举报
0/150
提交
取消