PHP+Mysql基于事务处理实现转账功能的方法
程序员文章站
2022-05-20 09:46:07
本文实例讲述了php+mysql基于事务处理实现转账功能的方法。分享给大家供大家参考。具体如下:
本文实例讲述了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');
希望本文所述对大家的php程序设计有所帮助。