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
<?php
header('content-type:text/html;charset=utf-8');
try{
$dsn='mysql:host=localhost;dbname=test';
$username='root';
$passwd='';
$options=array(PDO::ATTR_AUTOCOMMIT,0);
$pdo=new PDO($dsn, $username, $passwd, $options);
var_dump($pdo->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();
}