批次刪除是後台管理系統的高頻功能。本文提供從 HTML 表單設計、JavaScript 全選邏輯、PHP 後端接收陣列、SQL 安全建構到完整防禦措施的端到端實作指南。
<form method="POST" action="delete_batch.php" id="listForm">
<table>
<thead>
<tr>
<th><input type="checkbox" id="selectAll"> ID</th>
<th>用戶名</th>
<th>標題</th>
<th>內容</th>
</tr>
</thead>
<tbody>
<?php foreach ($rows as $row): ?>
<tr>
<td><input type="checkbox" name="ids[]" value="<?= htmlspecialchars($row['id']) ?>"></td>
<td><?= htmlspecialchars($row['user']) ?></td>
<td><?= htmlspecialchars($row['title']) ?></td>
<td><?= htmlspecialchars($row['content']) ?></td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
<button type="submit" name="action" value="delete" class="btn-danger">批次刪除</button>
</form>
關鍵點:name="ids[]" 讓 PHP 自動接收為陣列 $_POST['ids']。
<script>
document.getElementById('selectAll').addEventListener('change', function(e) {
document.querySelectorAll('input[name="ids[]"]').forEach(cb => cb.checked = e.target.checked);
});
// 可選:反選按鈕
document.getElementById('invertSelect')?.addEventListener('click', () => {
document.querySelectorAll('input[name="ids[]"]').forEach(cb => cb.checked = !cb.checked);
});
</script>
<?php
// delete_batch.php
declare(strict_types=1);
session_start();
require_once __DIR__ . '/conf/conn.php'; // PDO 連線
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
http_response_code(405);
exit('Method Not Allowed');
}
// CSRF 保護(簡易示範,生產請用專用庫)
if (!hash_equals($_SESSION['csrf_token'] ?? '', $_POST['csrf_token'] ?? '')) {
http_response_code(403);
exit('CSRF token invalid');
}
$ids = $_POST['ids'] ?? [];
if (!is_array($ids) || empty($ids)) {
header('Location: list.php?msg=未選擇任何項目');
exit;
}
// 1. 型別轉換與過濾:只保留正整數
$ids = array_map('intval', $ids);
$ids = array_filter($ids, fn($id) => $id > 0);
$ids = array_unique($ids); // 去重
if (empty($ids)) {
header('Location: list.php?msg=無效的 ID');
exit;
}
// 2. 權限檢查:確認當前用戶有權刪除這些記錄
// 此處略,實務需根據業務邏輯查詢擁有權
?>
<?php
// 建立佔位符:?,?,?
$placeholders = implode(',', array_fill(0, count($ids), '?'));
$sql = "DELETE FROM `message` WHERE `id` IN ($placeholders)";
$stmt = $pdo->prepare($sql);
$stmt->execute($ids); // 陣列自動綁定
$deleted = $stmt->rowCount();
$_SESSION['flash'] = "成功刪除 $deleted 筆留言";
header('Location: list.php');
exit;
?>
⚠ 安全警示:原文使用字串拼接
\"DELETE ... id in ($where)\"極度危險(SQL 注入)。務必使用預處理語句,佔位符數量動態產生。
<?php
try {
$pdo->beginTransaction();
$stmt = $pdo->prepare($sql);
$stmt->execute($ids);
$pdo->commit();
} catch (Throwable $e) {
$pdo->rollBack();
error_log("Batch delete failed: " . $e->getMessage());
header('Location: list.php?msg=刪除失敗,請稍後再試');
exit;
}
?>
ALTER TABLE `message` ADD COLUMN `deleted_at` DATETIME NULL DEFAULT NULL;
ALTER TABLE `message` ADD INDEX `idx_deleted_at` (`deleted_at`);
<?php
$placeholders = implode(',', array_fill(0, count($ids), '?'));
$sql = "UPDATE `message` SET `deleted_at` = NOW() WHERE `id` IN ($placeholders) AND `deleted_at` IS NULL";
$stmt = $pdo->prepare($sql);
$stmt->execute($ids);
?>
<?php
$auditSql = "INSERT INTO `delete_log` (`operator_id`, `target_table`, `target_ids`, `created_at`)
VALUES (?, 'message', ?, NOW())";
$auditStmt = $pdo->prepare($auditSql);
$auditStmt->execute([$_SESSION['user_id'], json_encode($ids)]);
?>
project/
├── conf/
│ └── conn.php # PDO 連線設定
├── list.php # 列表頁(含表單)
├── delete_batch.php # 批次刪除處理
├── templates/
│ └── flash.php # 訊息顯示元件
└── public/
└── js/
└── batch-select.js # 全選邏輯
| 問題 | 解決方案 |
|---|---|
| 勾選後未送出任何資料 | 確認 name="ids[]" 含方括號;表單 method="POST" |
| 刪除後頁面未重導 | 確認 header('Location: ...') 前無輸出;使用 exit |
| ID 含非數字導致錯誤 | array_map('intval', $ids) 強制轉整數 |
| 大量 ID 導致 SQL 過長 | 分批處理(每 500-1000 條)、或用臨時表 JOIN |
| CSRF token 驗證失敗 | 表單隱藏欄位 <input name="csrf_token" value="= $_SESSION['csrf_token'] ?>"> |
批次刪除看似簡單,實則涉及前端交互、輸入驗證、SQL 安全建構、權限控制、事務一致性與稽核追蹤。採用 PDO 預處理 + 陣列綁定 替代字串拼接,配合 CSRF 保護、型別強制轉換、軟刪除 與 稽核日誌,才能構建安全可靠的企業級刪除功能。