我有一个省的下拉列表,其默认值是根据从SQL中获取的用户省份确定的:
$getProvince = $db->prepare("
SELECT province
FROM users
WHERE userid = :id
");
$getProvince->execute(array(
':id' => $_SESSION["userident"]
));
$province = $getProvince->fetchColumn();
<select name="addprov">
<option value="AB" <?php if ($province == "AB") { echo "selected='selected'"; } ?>>Alberta</option>
<option value="BC" <?php if ($province == "BC") { echo "selected='selected'"; } ?>>British Columbia</option>
<option value="MB" <?php if ($province == "MB") { echo "selected='selected'"; } ?>>Manitoba</option>
<option value="NB" <?php if ($province == "NB") { echo "selected='selected'"; } ?>>New Brunswick</option>
<option value="NFLD" <?php if ($province == "NFLD") { echo "selected='selected'"; } ?>>Newfoundland & Labrador</option>
<option value="NS" <?php if ($province == "NS") { echo "selected='selected'"; } ?>>Nova Scotia</option>
<option value="ON" <?php if ($province == "ON") { echo "selected='selected'"; } ?>>Ontario</option>
<option value="PEI" <?php if ($province == "PEI") { echo "selected='selected'"; } ?>>Prince Edward Island</option>
<option value="QC" <?php if ($province == "QC") { echo "selected='selected'"; } ?>>Quebec</option>
<option value="SK" <?php if ($province == "SK") { echo "selected='selected'"; } ?>>Saskatchewan</option>
</select>
你可以看到这是多么丑陋。有没有一种优化方法,所以眼睛不是很难?
答案 0 :(得分:4)
将您的选项粘贴在数组中,然后循环html输出。
$provinces = array(
'AB' => 'Alberta',
'BC' => 'British Columbia',
'MB' => 'Manitoba',
//...
);
$province = ''; // your query result
然后输出......
<select name="addprov">
<?php foreach ($provinces as $key => $value): ?>
<option value="<?php echo $key; ?>" <?php if ($province === $key): ?>selected="selected"<?php endif; ?>><?php echo $value; ?></option>
<?php endforeach; ?>
</select>