$dsn = ‘mysql:dbname=wxadmin;host=127.0.0.1‘; $user = ‘root‘; $password = ‘‘; try{ $pdo = new PDO($dsn,$user,$password); $pdo->exec("set names utf8"); $pdo->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION); #开启异常模式 ( 提示的错误信息更具体 ) $pdo->setAttribute(PDO::ATTR_AUTOCOMMIT,0); #关闭自动提交 ( 使用事务前必须关闭 ) }catch(PDOException $es){ echo ‘Error: ‘.$es->getMessage(); } # id为1的用户 转账100元 给 id为2的用户 try{ $pdo->beginTransaction(); $sql = ‘UPDATE sw_test SET num = num - 100 WHERE id = 1 AND num >= 800‘; $affected_rows = $pdo->exec($sql); if($affected_rows==false || $affected_rows===false){ throw new PDOException("转出失败"); } $sql = ‘UPDATE sw_test SET num = num + 100 WHERE 2id = 2‘; $affected_rows = $pdo->exec($sql); if($affected_rows==false || $affected_rows===false){ throw new PDOException("转入失败"); } $pdo->commit(); echo ‘交易成功‘; }catch(PDOException $e){ $pdo->rollback(); // 只要捕获异常则回滚 echo $e->getMessage(); } // 事务结束 重新开启自动提交 $pdo->setAttribute(PDO::ATTR_AUTOCOMMIT,1);
时间: 2024-10-10 02:10:01