表單回顯、編輯頁面中,需根據數據庫值讓 `
<?php
// 假設 $row['wuyeleixing'] = 3 (來自數據庫)
$options = [
1 => '住宅',
2 => '辦公室',
3 => '營業房',
4 => '廠房',
5 => '倉庫',
// ...
];
?>
<select name="wuyeleixing">
<?php foreach ($options as $value => $label): ?>
<option value="<?= htmlspecialchars($value) ?>"
<?= ($row['wuyeleixing'] == $value) ? 'selected' : '' ?>
>
<?= htmlspecialchars($label) ?>
</option>
<?php endforeach; ?>
</select>
關鍵點:
htmlspecialchars() 防 XSS。<?php
// $row['dishu'] = 2
$radios = [
3 => '空白',
1 => '出讓',
2 => '劃撥',
4 => '集體',
];
?>
<?php foreach ($radios as $value => $label): ?>
<label>
<input type="radio" name="dishu" value="<?= htmlspecialchars($value) ?>"
<?= ($row['dishu'] == $value) ? 'checked' : '' ?>
>
<?= htmlspecialchars($label) ?>
</label>
<?php endforeach; ?>
注意:同組 Radio name 必須一致,`checked` 無值屬性,有即生效。
<?php
// $row['fujia_jiaju'] = 1 (或 true/'on')
$checked = !empty($row['fujia_jiaju']) ? 'checked' : '';
?>
<label>
<input type="checkbox" name="fujia_jiaju" value="jiaju" <?= $checked ?>>
家具
</label>
<?php
// 數據庫存儲:逗號分隔 'jiaju,chuju' 或 JSON 數組
$selected = explode(',', $row['fujia'] ?? ''); // ['jiaju', 'chuju']
$checkboxGroups = [
'jiaju' => '家具',
'chuju' => '廚具',
'woju' => '臥具',
'TV' => '電視機',
];
?>
<?php foreach ($checkboxGroups as $value => $label): ?>
<label>
<input type="checkbox" name="fujia[]" value="<?= htmlspecialchars($value) ?>"
<?= in_array($value, $selected) ? 'checked' : '' ?>
>
<?= htmlspecialchars($label) ?>
</label>
<?php endforeach; ?>
提交處理:`name="fujia[]"` 使 PHP 接收到數組 $_POST['fujia'] = ['jiaju', 'TV'],存儲時可 implode(',', $_POST['fujia']) 或 json_encode。
<?php
function form_selected($current, $target, $attr = 'selected') {
return ($current == $target) ? $attr : '';
}
function form_checked($current, $target) {
return ($current == $target) ? 'checked' : '';
}
// 使用
<option value="1" <?= form_selected($row['type'], 1) ?>>類型一</option>
<input type="radio" name="sex" value="1" <?= form_checked($row['sex'], 1) ?>>
<input type="checkbox" name="tag[]" value="news" <?= form_checked(in_array('news', $tags), true) ?>>
?>
htmlspecialchars() 轉義。