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

WBOY
发布: 2016-07-25 09:01:30
原创
1192 人浏览过
  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');
复制代码


来源:php.cn
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板