PHP transaction และการจัดการข้อผิดพลาดของฐานข้อมูล
ปัญหาที่ transaction แก้
โอนเงิน: หัก 500 จากบัญชี A แล้วเพิ่ม 500 ให้บัญชี B — 2 คำสั่ง UPDATE ถ้าคำสั่งที่ 2 พัง (ไฟดับ, error) เงินหายจากระบบ 500 บาท
transaction บอก DB ว่า “กลุ่มคำสั่งนี้เป็นหน่วยเดียว ทำสำเร็จทั้งหมด หรือย้อนกลับให้เหมือนไม่เคยทำ”
beginTransaction / commit / rollBack
<?php
declare(strict_types=1);
function transfer(PDO $pdo, int $fromId, int $toId, int $amountSatang): void
{
$pdo->beginTransaction();
try {
// หักจากต้นทาง — เช็คยอดพอในเงื่อนไข
$debit = $pdo->prepare(
'UPDATE accounts SET balance = balance - :amt
WHERE id = :id AND balance >= :amt'
);
$debit->execute(['amt' => $amountSatang, 'id' => $fromId]);
if ($debit->rowCount() === 0) {
throw new RuntimeException('ยอดเงินไม่พอ');
}
// เพิ่มให้ปลายทาง
$credit = $pdo->prepare(
'UPDATE accounts SET balance = balance + :amt WHERE id = :id'
);
$credit->execute(['amt' => $amountSatang, 'id' => $toId]);
if ($credit->rowCount() === 0) {
throw new RuntimeException('ไม่พบบัญชีปลายทาง');
}
$pdo->commit(); // ยืนยัน — บันทึกจริง
} catch (\Throwable $e) {
$pdo->rollBack(); // ยกเลิกทุกอย่างในบล็อกนี้
throw $e; // ส่งต่อให้คนเรียกรู้
}
}beginTransaction()— เริ่ม ตั้งแต่นี้การเปลี่ยนแปลงยังไม่ถาวรcommit()— ยืนยัน เขียนลงจริงrollBack()— ยกเลิก กลับไปสภาพก่อนbeginTransaction()- ทุก path ต้องจบที่
commitหรือrollBack— ใช้try/catchครอบ
helper รับ closure — กันลืม rollBack
รูปแบบที่นิยม: ห่อ logic ทั้งหมดไว้ใน closure แล้วให้ helper จัดการ begin/commit/rollback:
<?php
declare(strict_types=1);
function transaction(PDO $pdo, callable $work): mixed
{
if ($pdo->inTransaction()) {
return $work(); // อยู่ใน transaction แล้ว ไม่ซ้อน
}
$pdo->beginTransaction();
try {
$result = $work();
$pdo->commit();
return $result;
} catch (\Throwable $e) {
$pdo->rollBack();
throw $e;
}
}ใช้งาน:
<?php
$orderId = transaction($pdo, function () use ($pdo, $cart, $userId) {
// 1. สร้างออเดอร์
$stmt = $pdo->prepare('INSERT INTO orders (user_id, total) VALUES (?, ?)');
$stmt->execute([$userId, $cart->total()]);
$orderId = (int) $pdo->lastInsertId();
// 2. เพิ่มรายการสินค้า + ตัดสต็อก
$item = $pdo->prepare('INSERT INTO order_items (order_id, product_id, qty) VALUES (?, ?, ?)');
$stock = $pdo->prepare('UPDATE products SET stock = stock - :q WHERE id = :id AND stock >= :q');
foreach ($cart->items() as $line) {
$item->execute([$orderId, $line->productId, $line->qty]);
$stock->execute(['q' => $line->qty, 'id' => $line->productId]);
if ($stock->rowCount() === 0) {
throw new RuntimeException("สินค้า {$line->productId} สต็อกไม่พอ");
}
}
return $orderId;
});ถ้าสินค้าชิ้นสุดท้ายสต็อกไม่พอ → throw → rollback → ออเดอร์และการตัดสต็อกก่อนหน้า หายหมด เหมือนไม่เคยเกิด
auto-commit
นอก transaction ทุกคำสั่งถูก commit ทันที (auto-commit) — INSERT เดี่ยว ๆ ไม่ต้องมี transaction เอง transaction มีค่าเมื่อ หลายคำสั่งต้องสอดคล้องกัน หรือเมื่อ insert จำนวนมาก (เร็วขึ้นมาก):
<?php
$pdo->beginTransaction();
$stmt = $pdo->prepare('INSERT INTO logs (msg) VALUES (?)');
foreach ($thousandsOfRows as $row) {
$stmt->execute([$row]);
}
$pdo->commit(); // เขียน disk ครั้งเดียว แทนหลายพันครั้งจับ error เฉพาะทาง
PDOException มี errorInfo — [SQLSTATE, driver code, message] ใช้แยกประเภท error:
<?php
try {
$stmt = $pdo->prepare('INSERT INTO users (email) VALUES (?)');
$stmt->execute([$email]);
} catch (\PDOException $e) {
// 23000 = integrity constraint violation (unique, foreign key, not null)
if ($e->getCode() === '23000') {
throw new RuntimeException('อีเมลนี้ถูกใช้แล้ว', previous: $e);
}
throw $e;
}SQLSTATE ที่เจอบ่อย: 23000 (constraint), HY000 (ทั่วไป/lock), 40001 (deadlock — ควร retry)
deadlock และ retry
เมื่อสอง transaction ล็อกแถวไขว้กัน DB จะฆ่าตัวหนึ่ง (40001 / 1213) — วิธีจัดการคือ retry:
<?php
function transactionWithRetry(PDO $pdo, callable $work, int $maxRetries = 3): mixed
{
for ($attempt = 1; ; $attempt++) {
try {
return transaction($pdo, $work);
} catch (\PDOException $e) {
$isDeadlock = in_array($e->errorInfo[1] ?? 0, [1213, 1205], true);
if (!$isDeadlock || $attempt >= $maxRetries) {
throw $e;
}
usleep(random_int(50_000, 200_000) * $attempt); // หน่วงแบบสุ่มเพิ่มขึ้น
}
}
}ข้อควรระวังเรื่อง DDL
ใน MySQL คำสั่ง DDL (CREATE TABLE, ALTER TABLE, DROP) ทำให้ transaction ปัจจุบัน commit อัตโนมัติ (implicit commit) — rollBack() หลังจากนั้นจะไม่ย้อน DDL อย่ารัน migration ปนกับ transaction ของข้อมูล (PostgreSQL และ SQLite ทำ DDL ใน transaction ได้)
เรื่องที่คนมักพลาด
beginTransaction()แล้วไม่มีrollBack()ใน catch — เกิด error แล้ว transaction ค้าง ล็อกแถวไว้ คำขออื่นรอจน timeout ใช้ helper รับ closure- ซ้อน
beginTransaction()— PDO ไม่รองรับ nested transaction โดยตรง (โยน error) เช็คinTransaction()ก่อน หรือใช้ savepoint commit()แต่ลืมว่าบาง path ออกก่อนถึง — เช่นreturnกลางคัน แล้ว transaction ไม่ถูกปิด- ทำ transaction ครอบงานที่นานมาก (เรียก API ภายนอก, ประมวลผลไฟล์ใหญ่) — ล็อกแถวไว้นาน กระทบคำขออื่น ทำงานหนักนอก transaction แล้วค่อย begin
- คิดว่า transaction กัน race condition ทุกแบบ — ต้องมี
WHERE ... AND balance >= :amt/AND stock >= :qหรือใช้SELECT ... FOR UPDATEล็อกแถวก่อน ไม่งั้นสองคนตัดสต็อกชิ้นสุดท้ายพร้อมกันได้ - ไม่ retry deadlock — traffic สูงจะเจอ error สุ่ม ๆ ที่จริงแค่ retry ก็ผ่าน
- รัน
ALTER TABLEใน transaction บน MySQL แล้วคาดว่า rollback ได้
สรุป
- transaction = “สำเร็จทั้งหมด หรือย้อนกลับทั้งหมด” —
beginTransaction()/commit()/rollBack() - ครอบด้วย
try/catchเสมอ,rollBack()ใน catch แล้วthrowต่อ — หรือใช้ helpertransaction($pdo, fn() => ...) - ใช้เมื่อหลายคำสั่งต้องสอดคล้อง (โอนเงิน, ออเดอร์+สต็อก) หรือ insert จำนวนมาก (เร็วขึ้น)
- constraint violation = SQLSTATE
23000, deadlock = code1213(ควร retry แบบหน่วงสุ่ม) - ยังต้องมีเงื่อนไขใน
WHERE(balance >= :amt) — transaction ไม่ได้กัน race ให้เอง - MySQL: DDL commit อัตโนมัติ — อย่าปนกับ transaction ข้อมูล
จบเฟสฐานข้อมูล บทถัดไปเข้าเฟสความปลอดภัย เริ่มที่การเก็บรหัสผ่าน — password_hash() / password_verify() และเหตุผลที่ห้าม md5/sha1