**名稱必須加上 `[]`**,PHP 才會自動將多個同名 checkbox 值組成陣列:
<form method="post" action="">
<label><input type="checkbox" name="colors[]" value="red"> 紅色</label>
<label><input type="checkbox" name="colors[]" value="green"> 綠色</label>
<label><input type="checkbox" name="colors[]" value="blue"> 藍色</label>
<input type="submit" value="送出">
</form>
<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
// 未勾選時 $_POST['colors'] 不存在,需先判斷
$colors = $_POST['colors'] ?? [];
// 安全過濾:移除非預期值
$allowed = ['red', 'green', 'blue'];
$colors = array_intersect($colors, $allowed);
if ($colors) {
echo '你選擇了:' . implode(', ', $colors);
} else {
echo '請至少選擇一項';
}
}
?>
<?php
$options = [
1 => '方案 A',
2 => '方案 B',
3 => '方案 C',
];
?>
<form method="post">
<?php foreach ($options as $id => $label): ?>
<label>
<input type="checkbox" name="plan_ids[]" value="<?= $id ?>">
<?= htmlspecialchars($label) ?>
</label>
<?php endforeach; ?>
<button type="submit">送出</button>
</form>
<?php
if ($_POST) {
$ids = array_map('intval', $_POST['plan_ids'] ?? []);
// 後續可用 $ids 查詢資料庫 WHERE id IN (...)
}
?>
| 錯誤 | 現象 | 解決 |
|---|---|---|
| name 未加 [] | 只取到最後一個值 | name="colors[]" |
| 未檢查 isset | 未勾選時 Notice: Undefined index | 用 ?? [] 或 isset() |
| 直接用於 SQL | SQL Injection 風險 | intval / prepared statement |
| 未過濾非法值 | 竄改 value 提交 | array_intersect 白名單 |
<script>
function toggleAll(source) {
document.querySelectorAll('input[name="colors[]"]').forEach(cb => cb.checked = source.checked);
}
</script>
<label><input type="checkbox" onchange="toggleAll(this)"> 全選</label>
原始來源:www.111cn.net