[PDO]①⑥--事务处理

[PDO]①⑥--事务处理_第1张图片
Paste_Image.png
mysql> CREATE TABLE userAccount(
    -> id TINYINT UNSIGNED AUTO_INCREMENT KEY,
    -> username VARCHAR(20) NOT NULL UNIQUE,
    -> money DECIMAL(10,2)
    -> )ENGINE=INNODB;
Query OK, 0 rows affected (0.05 sec)

mysql> INSERT userAccount(username,money) VALUES('imooc',10000),('king',5000);
Query OK, 2 rows affected (0.16 sec)
Records: 2  Duplicates: 0  Warnings: 0
inTransaction());
    //开启事务
    $pdo->beginTransaction();
    var_dump($pdo->inTransaction());
    //$sql='UPDATE userAccount SET money=money-2000 WHERE username="imooc"';
    $sql='UPDATE userAccount SET money=money-2000 WHERE username="imooc"';

    $res1=$pdo->exec($sql);
    if($res1==0){
        throw new PDOException('imooc 转账失败');
    }
    $res2=$pdo->exec('UPDATE userAccount SET money=money+2000 WHERE username="king"');
    if($res2==0){
        throw new PDOException('king 接收失败');
    }
    //提交事务
    $pdo->commit();
}catch(PDOException $e){
    //回滚事务
    $pdo->rollBack();
    echo $e->getMessage();
}
Paste_Image.png
[PDO]①⑥--事务处理_第2张图片
Paste_Image.png

你可能感兴趣的:([PDO]①⑥--事务处理)