0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

PDOでロールバックして帳消し

Posted at

phpでロールバックをして帳消しします。

try{
    $pdo = new PDO($dns,$user,$pass,[
    PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
]);}catch(PDOException $e){
    echo '接続失敗' . $e->getMessage();
    exit();
}

$pdo->beginTransaction(); //トランザクションの開始
$pdo->query(
    "UPDATE user SET age = age + 1 WHERE id = 1"
);
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
print_r($result[0]["age"]);
26

間違えたことに気づきます。処理前まで巻き戻しましょう。

$pdo->rollback();
print_r($result[0]["age"]);
25

rollbackメソッドを実行することで$pdo->beginTransaction()のところまで巻き戻しています。
ちなみに以下のやり方だとエラーが出ます。

try{
    $pdo = new PDO($dns,$user,$pass,[
    PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
]);}catch(PDOException $e){
    echo '接続失敗' . $e->getMessage();
    exit();
}

$pdo->beginTransaction(); //トランザクションの開始
$pdo->query(
    "UPDATE user SET age = age + 1 WHERE id = 1"
);
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
print_r($result[0]["age"]);
$pdo->commit(); //ここでコミットする

$pdo->rollback(); //コミットした後にrollbackメソッドを実行する
print_r($result[0]["age"]);
Fatal error: Uncaught PDOException: There is no active transaction in

また今度勉強しようと思います。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?