首页 > 开发 > PHP > 正文

PHP+Mysql基于事务处理实现转账功能的方法

2024-05-04 23:37:29
字体:大 中 小
来源:转载
供稿:网友

这篇文章主要介绍了PHP+Mysql基于事务处理实现转账功能的方法,实例分析了mysql事务处理的使用技巧,具有一定参考借鉴价值,需要的朋友可以参考下

本文实例讲述了PHP+Mysql基于事务处理实现转账功能的方法。分享给大家供大家参考。具体如下:

 

 
  1. <?php 
  2. header("Content-Type:text/html;charset=utf-8"); 
  3. $mysqli=new mysqli("localhost","root","","test"); 
  4. if(mysqli_connect_errno()) 
  5. { 
  6. printf("连接失败:%s<br>",mysqli_connect_error()); 
  7. exit(); 
  8. } 
  9. $success=TRUE; 
  10. $price=8000; 
  11. $result=$mysqli->query("select cash from account where name='userA'"); 
  12. while($row=$result->fetch_assoc()) 
  13. { 
  14. $value=$row["cash"]; 
  15. echo $value; 
  16. } 
  17. $mysqli->autocommit(0); 
  18. if($value>=$price){ 
  19. $result=$mysqli->query("UPDATE account set cash=cash-$price where name='userA'"); 
  20. }else { 
  21. echo '余额不足'; 
  22. exit(); 
  23. } 
  24. if(!$result or $mysqli->affected_rows!=1) 
  25. { 
  26. $success=FALSE; 
  27. } 
  28. $result=$mysqli->query("UPDATE account set cash=cash+$price where name='userB'"); 
  29. if(!result or $mysqli->affected_rows!=1){ 
  30. $success=FALSE; 
  31. } 
  32. if($success) 
  33. { 
  34. $mysqli->commit(); 
  35. echo '转账成功!'; 
  36. }else 
  37. { 
  38. $mysqli->rollback(); 
  39. echo "转账失败!"; 
  40. } 
  41. $mysqli->autocommit(1); 
  42. $query="select cash from account where name=?"; 
  43. $stmt=$mysqli->prepare($query); 
  44. $stmt->bind_param('s',$name); 
  45. $name='userA'; 
  46. $stmt->execute(); 
  47. $stmt->store_result(); 
  48. $stmt->bind_result($cash); 
  49. while($stmt->fetch()) 
  50. echo "用户userA的值为:".$cash; 
  51. $mysqli->close(); 
  52. ?> 

数据库SQL语句如下:

 

 
  1. create table account{ 
  2. userID smallint unsigned not null auto_increment, 
  3. name varchar(45) not null, 
  4. cash decimal(9,2) not null, 
  5. primary key(userID) 
  6. )type=InnoDB; 
  7. insert into account(name,cash) values ('userA','2000'); 
  8. insert into account(name,cash) values ('userB','10000'); 

希望本文所述对大家的php程序设计有所帮助。

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表