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

  • <?php
  •   header("Content-Type:text/html;charset=utf-8");
  •   $mysqli=new mysqli("localhost","root","","test");
  •   if(mysqli_connect_errno())
  •   {
  •   printf("连接失败:%s<br>",mysqli_connect_error());
  •   exit();
  •   }
  •   $success=TRUE;
  •   $price=8000;
  •   $result=$mysqli->query("select cash from account where name='userA'");
  •   while($row=$result->fetch_assoc())
  •   {
  •   $value=$row["cash"];
  •   echo $value;
  •   }
  •   $mysqli->autocommit(0);
  •   if($value>=$price){
  •   $result=$mysqli->query("UPDATE account set cash=cash-$price where name='userA'");
  •   }else {
  •   echo '余额不足';
  •   exit();
  •   }
  •   if(!$result or $mysqli->affected_rows!=1)
  •   {
  •   $success=FALSE;
  •   }
  •   $result=$mysqli->query("UPDATE account set cash=cash+$price where name='userB'");
  •   if(!result or $mysqli->affected_rows!=1){
  •   $success=FALSE;
  •   }
  •   if($success)
  •   {
  •   $mysqli->commit();
  •   echo '转账成功!';
  •   }else
  •   {
  •   $mysqli->rollback();
  •   echo "转账失败!";
  •   }
  •   $mysqli->autocommit(1);
  •   $query="select cash from account where name=?";
  •   $stmt=$mysqli->prepare($query);
  •   $stmt->bind_param('s',$name);
  •   $name='userA';
  •   $stmt->execute();
  •   $stmt->store_result();
  •   $stmt->bind_result($cash);
  •   while($stmt->fetch())
  •   echo "用户userA的值为:".$cash;
  •   $mysqli->close();
  • ?>
  • 数据库SQL语句如下:
  • create table account{
  •  userID smallint unsigned not null auto_increment,
  •  name varchar(45) not null,
  •  cash decimal(9,2) not null,
  •  primary key(userID)
  • )type=InnoDB;
  • insert into account(name,cash) values ('userA','2000');
  • insert into account(name,cash) values ('userB','10000');

 

转载于:https://www.cnblogs.com/ghjbk/p/6753818.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值