HTML 多選框要提交為數組,name 屬性必須以 [] 結尾 (如 name="colors[]"),PHP 才會自動將勾選的值組裝為 $_POST['colors'] 數組。
<!DOCTYPE html>
<html lang="zh-Hant">
<head>
<meta charset="UTF-8">
<title>多選框演示</title>
<style>
.checkbox-group { display: flex; flex-wrap: wrap; gap: 1rem; margin: 1rem 0; }
.checkbox-item { display: flex; align-items: center; gap: 0.3rem; }
</style>
</head>
<body>
<h2>選擇您喜歡的水果</h2>
<form method="post" action="">
<div class="checkbox-group">
<label class="checkbox-item"><input type="checkbox" name="fruits[]" value="apple"> 蘋果</label>
<label class="checkbox-item"><input type="checkbox" name="fruits[]" value="banana"> 香蕉</label>
<label class="checkbox-item"><input type="checkbox" name="fruits[]" value="orange"> 橘子</label>
<label class="checkbox-item"><input type="checkbox" name="fruits[]" value="grape"> 葡萄</label>
<label class="checkbox-item"><input type="checkbox" name="fruits[]" value="mango"> 芒果</label>
</div>
<button type="submit" name="submit">提交</button>
</form>
<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['submit'])) {
$fruits = $_POST['fruits'] ?? [];
if (empty($fruits)) {
echo '請至少選擇一項!
';
} else {
echo '您選擇了:
';
foreach ($fruits as $fruit) {
echo '- ' . htmlspecialchars($fruit) . '
';
}
echo '
';
echo '原始數組:
' . htmlspecialchars(print_r($fruits, true)) . '
';
}
}
?>
</body>
</html>
<?php
// 確保是數組,防止注入字符串導致 foreach 警告
$fruits = (array)($_POST['fruits'] ?? []);
// 過濾空值、去重、白名單驗證
$allowed = ['apple', 'banana', 'orange', 'grape', 'mango'];
$fruits = array_values(array_unique(array_intersect($fruits, $allowed)));
// 結果: 乾淨、索引重排、僅含合法值的數組
?>
<?php
// 方案 A: JSON 存儲 (推薦,靈活查詢)
$json = json_encode($fruits, JSON_UNESCAPED_UNICODE);
$stmt = $pdo->prepare("UPDATE users SET preferences = ? WHERE id = ?");
$stmt->execute([$json, $userId]);
// 方案 B: 關聯表 (規範化)
$stmt = $pdo->prepare("DELETE FROM user_fruits WHERE user_id = ?");
$stmt->execute([$userId]);
$ins = $pdo->prepare("INSERT INTO user_fruits (user_id, fruit) VALUES (?, ?)");
foreach ($fruits as $fruit) {
$ins->execute([$userId, $fruit]);
}
?>
<?php
// 從數據庫讀取
$stored = json_decode($user['preferences'], true) ?? [];
?>
'蘋果','banana'=>'香蕉','orange'=>'橘子','grape'=>'葡萄','mango'=>'芒果'] as $val => $label): ?>
<script>
document.addEventListener('DOMContentLoaded', () => {
const checkboxes = document.querySelectorAll('input[name="fruits[]"]');
const selectAll = document.getElementById('select-all');
const invert = document.getElementById('invert');
const getValues = document.getElementById('get-values');
selectAll?.addEventListener('click', () => {
checkboxes.forEach(cb => cb.checked = true);
});
invert?.addEventListener('click', () => {
checkboxes.forEach(cb => cb.checked = !cb.checked);
});
getValues?.addEventListener('click', () => {
const values = Array.from(checkboxes)
.filter(cb => cb.checked)
.map(cb => cb.value);
alert('選中: ' + values.join(', '));
});
// AJAX 提交
document.querySelector('form').addEventListener('submit', async (e) => {
e.preventDefault();
const formData = new FormData(e.target);
// FormData 會自動處理同名多值為數組
const res = await fetch('api/save_preferences.php', {
method: 'POST',
body: formData
});
const data = await res.json();
alert(data.message);
});
});
</script>
| 問題 | 原因 | 解決 |
|---|---|---|
| 未勾選時 $_POST 無該鍵 | 瀏覽器不發送未勾選 checkbox | 用 $_POST['fruits'] ?? [] 兜底 |
| 只收到最後一個值 | name 未加 [] | name="fruits[]" (PHP 特有約定) |
| 索引不連續 (0,2,3) | 未勾選的不提交 | array_values() 重建索引 |
| XSS 風險 | 直接輸出用戶提交值 | htmlspecialchars() 輸出轉義 |
| SQL 注入 | 拼接 SQL | 預處理語句 + 白名單驗證 |
<?php
$options = $pdo->query("SELECT id, name FROM categories WHERE status=1 ORDER BY sort")->fetchAll(PDO::FETCH_KEY_PAIR);
?>
$name): ?>
PHP 處理 Checkbox 核心在於 name="field[]" 約定。配合白名單驗證、JSON/關聯表存儲、回顯邏輯、JS 增強,構建完整、安全、用戶友好的多選交互。現代框架 (Laravel/Symfony) 表單組件已封裝最佳實踐,建議直接使用。