php PDO事务的简单应用

 query("set names utf8");
	}catch(PDOException $e){
		exit($e->getMessage());
	}
	try{
		$sql = "SELECT `money` from bank WHERE `name`='张三'";
		$arr = $pdo->query($sql)->fetch(PDO::FETCH_ASSOC);
		if ($arr['money']<=100) {
			exit("对不起!您的余额不足");
		}else{
			$pdo->beginTransaction();//开启事务
			$sql = "UPDATE bank SET `money`=`money`-100 WHERE `name`='张三'";
			$info = $pdo->exec($sql);
			if (!$info) {
				throw new PDOException('对不起,转账失败,转账金额已退还!');
			}
			$sql = "UPDATE bank SET `money`=`money`+100 WHERE `name`='李四'";
			$info = $pdo->exec($sql);
			if (!$info) {
				throw new PDOException('对不起,李四未收到转账金额!');
			}
			$pdo->commit();  //事务提交,注意这里的提交默认为自动提交
			exit("转账成功!");
		}
	}catch(PDOException $e){
		$pdo->rollback();  //事务回滚
		exit($e->getMessage());
	}

你可能感兴趣的:(php,php)