<?php
if ($_POST['chk']) {
$sid = implode(',', $_POST['chk']);
$query = mysql_query("delete from news where news_id in ($sid)");
// ...
}
四大風險:
$_POST['chk'] 未驗證直接拼接,攻擊者可提交 1; DROP TABLE news;--。implode(',', []) 返回空字串,SQL 變為 IN () 報錯。<?php
// config.php - 資料庫連接單例
$pdo = new PDO('mysql:host=localhost;dbname=cms;charset=utf8mb4', 'user', 'pass', [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES => false,
]);
// delete_batch.php
session_start();
header('Content-Type: application/json; charset=utf-8');
try {
// 1. CSRF 驗證
if (!hash_equals($_SESSION['csrf_token'] ?? '', $_POST['csrf_token'] ?? '')) {
throw new Exception('CSRF token 無效', 403);
}
// 2. 獲取並驗證 ID 列表
$ids = $_POST['ids'] ?? [];
if (!is_array($ids) || empty($ids)) {
throw new Exception('未選擇任何項目', 400);
}
// 3. 過濾:只保留正整數
$ids = array_filter($ids, fn($id) => ctype_digit((string)$id));
$ids = array_map('intval', $ids);
$ids = array_unique($ids);
if (empty($ids)) {
throw new Exception('無效的 ID 列表', 400);
}
// 4. 可選:權限檢查 (確認當前用戶有權刪除這些記錄)
// $allowed = $pdo->query("SELECT news_id FROM news WHERE news_id IN (".implode(',',$ids).") AND author_id={$userId}")->fetchAll(PDO::FETCH_COLUMN);
// $ids = array_intersect($ids, $allowed);
// 5. 事務執行批量刪除
$pdo->beginTransaction();
// 動態生成佔位符: ?,?,?
$placeholders = implode(',', array_fill(0, count($ids), '?'));
$sql = "DELETE FROM news WHERE news_id IN ($placeholders)";
$stmt = $pdo->prepare($sql);
$stmt->execute($ids);
$deleted = $stmt->rowCount();
$pdo->commit();
echo json_encode([
'success' => true,
'deleted' => $deleted,
'message' => "成功刪除 $deleted 條記錄"
]);
} catch (Exception $e) {
if ($pdo->inTransaction()) $pdo->rollBack();
http_response_code($e->getCode() ?: 500);
error_log("Batch delete error: " . $e->getMessage());
echo json_encode(['success' => false, 'message' => $e->getMessage()]);
}
<!-- 列表頁 -->
<form id="batchForm" method="post">
<input type="hidden" name="csrf_token" value="<?= $_SESSION['csrf_token'] = bin2hex(random_bytes(32)) ?>">
<table>
<thead>
<tr><th><input type="checkbox" id="checkAll"></th><th>標題</th><th>操作</th></tr>
</thead>
<tbody>
<?php foreach ($news as $item): ?>
<tr>
<td><input type="checkbox" name="ids[]" value="<?= $item['news_id'] ?>" class="row-check"></td>
<td><?= htmlspecialchars($item['title']) ?></td>
<td><a href="edit.php?id=<?= $item['news_id'] ?>">編輯</a></td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
<button type="button" id="btnBatchDelete" class="btn-danger" disabled>批量刪除 (<span id="selCount">0</span>)</button>
</form>
<script>
const form = document.getElementById('batchForm');
const checkAll = document.getElementById('checkAll');
const rowChecks = document.querySelectorAll('.row-check');
const btnDelete = document.getElementById('btnBatchDelete');
const selCount = document.getElementById('selCount');
function updateUI() {
const checked = form.querySelectorAll('input[name="ids[]"]:checked');
const count = checked.length;
selCount.textContent = count;
btnDelete.disabled = count === 0;
}
checkAll.addEventListener('change', () => {
rowChecks.forEach(cb => cb.checked = checkAll.checked);
updateUI();
});
rowChecks.forEach(cb => cb.addEventListener('change', updateUI));
btnDelete.addEventListener('click', async () => {
if (!confirm('確定要刪除選中的項目嗎?此操作不可恢復!')) return;
btnDelete.disabled = true;
btnDelete.textContent = '刪除中...';
const formData = new FormData(form);
try {
const res = await fetch('delete_batch.php', {method: 'POST', body: formData});
const data = await res.json();
if (data.success) {
alert(data.message);
location.reload(); // 或移除對應 DOM 行
} else {
alert('失敗: ' + data.message);
}
} catch (e) {
alert('請求異常: ' + e.message);
} finally {
btnDelete.disabled = false;
btnDelete.innerHTML = '批量刪除 (0)';
updateUI();
}
});
</script>
原代碼無 confirm() 阻斷,且 if($_POST['chk']) 只要陣列非空即執行。瀏覽器原生 confirm() 返回 false 時需阻止表單提交:
<form onsubmit="return confirm('確定刪除?')"> ... </form>
// 或 JS 阻止
form.addEventListener('submit', e => { if(!confirm('...')) e.preventDefault(); });
-- 資料表增加欄位
ALTER TABLE news ADD COLUMN deleted_at DATETIME NULL DEFAULT NULL;
ALTER TABLE news ADD INDEX idx_deleted (deleted_at);
-- 批量軟刪除
UPDATE news SET deleted_at = NOW() WHERE news_id IN (?,?,?) AND deleted_at IS NULL;
-- 查詢時自動排除
SELECT * FROM news WHERE deleted_at IS NULL;
-- 或建立 VIEW
CREATE VIEW news_active AS SELECT * FROM news WHERE deleted_at IS NULL;
優點:資料可恢復、審計追蹤、避免外鍵約束衝突、符合 GDPR 等合規要求。