欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  后端开发

Mysql事务处理(一个转账程序)

程序员文章站 2022-04-20 11:48:30
...
  1. header("Content-Type:text/html;charset=utf-8");
  2. $mysqli=new mysqli("localhost","root","","test");
  3. if(mysqli_connect_errno())
  4. {
  5. printf("连接失败:%s
    ",mysqli_connect_error());
  6. exit();
  7. }
  8. $success=TRUE;
  9. $price=8000;
  10. $result=$mysqli->query("select cash from account where name='userA'");
  11. while($row=$result->fetch_assoc())
  12. {
  13. $value=$row["cash"];
  14. echo $value;
  15. }
  16. $mysqli->autocommit(0);
  17. if($value>=$price){
  18. $result=$mysqli->query("UPDATE account set cash=cash-$price where name='userA'");
  19. }else {
  20. echo '余额不足';
  21. exit();
  22. }
  23. if(!$result or $mysqli->affected_rows!=1)
  24. {
  25. $success=FALSE;
  26. }
  27. $result=$mysqli->query("UPDATE account set cash=cash+$price where name='userB'");
  28. if(!result or $mysqli->affected_rows!=1){
  29. $success=FALSE;
  30. }
  31. if($success)
  32. {
  33. $mysqli->commit();
  34. echo '转账成功!';
  35. }else
  36. {
  37. $mysqli->rollback();
  38. echo "转账失败!";
  39. }
  40. $mysqli->autocommit(1);
  41. $query="select cash from account where name=?";
  42. $stmt=$mysqli->prepare($query);
  43. $stmt->bind_param('s',$name);
  44. $name='userA';
  45. $stmt->execute();
  46. $stmt->store_result();
  47. $stmt->bind_result($cash);
  48. while($stmt->fetch())
  49. echo "用户userA的值为:".$cash;
  50. $mysqli->close();
  51. ?>
  52. &&&&&&&&&&&&&&&&&&
  53. create table account{
  54. userID smallint unsigned not null auto_increment,
  55. name varchar(45) not null,
  56. cash decimal(9,2) not null,
  57. primary key(userID)
  58. )type=InnoDB;
  59. insert into account(name,cash) values ('userA','2000');
  60. insert into account(name,cash) values ('userB','10000');
复制代码