處理表單批量提交是後台管理常見需求。本文介紹兩種核心模式:批量新增(多筆 INSERT)與 批量更新(多筆 UPDATE),並說明陣列式表單命名與迴圈處理技巧。
在 HTML 表單中,將同類欄位命名為陣列格式(如 name="field[]"),PHP 接收時會自動轉為陣列:
<input name="sp_name[]" type="text">
<input name="sp_name[]" type="text">
<input name="sp_name[]" type="text">
<form method="post" action="insert_batch.php">
<table>
<tr><th>商品名稱</th><th>編號</th><th>單價</th><th>數量</th><th>產地</th></tr>
<tr>
<td><input name="sp_name[]" type="text"></td>
<td><input name="sp_number[]" type="text"></td>
<td><input name="price[]" type="text"></td>
<td><input name="counts[]" type="text"></td>
<td><input name="address[]" type="text"></td>
</tr>
<tr>
<td><input name="sp_name[]" type="text"></td>
<td><input name="sp_number[]" type="text"></td>
<td><input name="price[]" type="text"></td>
<td><input name="counts[]" type="text"></td>
<td><input name="address[]" type="text"></td>
</tr>
<!-- 可動態 JS 新增更多列 -->
</table>
<button type="submit">批量新增</button>
</form>
<?php
$pdo = new PDO('mysql:host=localhost;dbname=test;charset=utf8', 'root', 'password');
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$names = $_POST['sp_name'] ?? [];
$numbers = $_POST['sp_number'] ?? [];
$prices = $_POST['price'] ?? [];
$counts = $_POST['counts'] ?? [];
$addresses= $_POST['address'] ?? [];
$count = count($names);
$success = 0;
$sql = "INSERT INTO tb_products (sp_name, sp_number, price, counts, address) VALUES (?, ?, ?, ?, ?)";
$stmt = $pdo->prepare($sql);
$pdo->beginTransaction();
try {
for ($i = 0; $i < $count; $i++) {
// 簡單驗證:跳過空白列
if (trim($names[$i]) === '') continue;
$stmt->execute([
$names[$i],
$numbers[$i],
$prices[$i],
$counts[$i],
$addresses[$i],
]);
$success++;
}
$pdo->commit();
echo "成功新增 $success 筆資料";
} catch (Exception $e) {
$pdo->rollBack();
echo "新增失敗:" . $e->getMessage();
}
}
?>
<form method="post" action="update_batch.php">
<table>
<tr><th>選取</th><th>帳號</th><th>權限</th><th>狀態</th></tr>
<?php foreach ($users as $user): ?>
<tr>
<td><input type="checkbox" name="ids[]" value="<?= $user['id'] ?>"></td>
<td><?= htmlspecialchars($user['username']) ?></td>
<td><?= htmlspecialchars($user['role']) ?></td>
<td><?= $user['status'] ?></td>
</tr>
<?php endforeach; ?>
</table>
<button type="submit" name="action" value="activate">啟用</button>
<button type="submit" name="action" value="deactivate">停用</button>
</form>
<?php
$pdo = new PDO('mysql:host=localhost;dbname=test;charset=utf8', 'root', 'password');
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$ids = $_POST['ids'] ?? [];
$action = $_POST['action'] ?? '';
if (empty($ids)) {
echo "請至少選取一項";
exit;
}
$statusMap = [
'activate' => '啟用',
'deactivate' => '停用',
];
$newStatus = $statusMap[$action] ?? null;
if (!$newStatus) exit('無效操作');
// 使用 IN 子句單次更新,效能優於迴圈
$placeholders = implode(',', array_fill(0, count($ids), '?'));
$sql = "UPDATE tb_users SET status = ? WHERE id IN ($placeholders)";
$stmt = $pdo->prepare($sql);
$params = array_merge([$newStatus], $ids);
try {
$stmt->execute($params);
echo "成功更新 {$stmt->rowCount()} 筆資料";
} catch (Exception $e) {
echo "更新失敗:" . $e->getMessage();
}
}
?>
| 場景 | 表單命名 | PHP 處理 | SQL 策略 |
|---|---|---|---|
| 批量新增 | name="field[]" | for 迴圈遍歷 | Prepared Statement + Transaction |
| 批量更新 | name="ids[]" (checkbox) | 取得陣列直接 IN 查詢 | 單條 UPDATE ... WHERE id IN (...) |
IN 子句單次執行,避免 N 次往返資料庫LOAD DATA INFILE / 多值 INSERT希望本文對您的 PHP 批量資料處理開發有所幫助。