0
0

PDO トランザクション

Last updated at Posted at 2024-04-07

PDO トランザクション beginTransaction, commit, rollback の3種類のメソッドを使用する

トランザクション: まとめて処理

  • 参考: PDOクラス

  • 使用されるシチュエーション例:
    銀行ATM: 残高を確認->Aさんから引き落とし->Bさんに振込などこれらを全部まとめて処理をする(もし、何か問題があれば元に戻す)。

index.php
<?php

require 'db_connection.php';

$sql = 'select * from contacts where id = :id'; // ? を付けるか : を付ける(プレースホルダ)

// トランザクション: まとめて処理 beginTransaction, commit, rollback
$pdo->beginTransaction(); // トランザクションを始める

try {
    // sql処理
    $stmt = $pdo->prepare($sql);
    $stmt->bindValue('id', 2, PDO::PARAM_INT);
    $stmt->execute();
    // 他にもsql処理があればこの中で追加していく
    $pdo->commit(); // 処理をまとめて実行
} catch (PDOException $e) {
    $pdo->rollBack(); // 更新のキャンセル(元に戻す)
}

例外で書く try{} catch(){}

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0