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

yipeiwu_com6年前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程序设计有所帮助。

相关文章

PHP+Mysql实现多关键字与多字段生成SQL语句的函数

本文实例讲述了PHP+Mysql实现多关键字与多字段生成SQL语句的函数的方法。分享给大家供大家参考。具体实现方法如下: 先看实例: 复制代码 代码如下:$keyword="1 2 3"...

PHP实现清除MySQL死连接的方法

本文实例讲述了PHP实现清除MySQL死连接的方法。分享给大家供大家参考,具体如下: 连接的情况,主要表现为有过多的Sleep连接,并且Time时间很长,占满了所有的可用连接数,以至于其...

PHP+Mysql+jQuery实现动态展示信息

在本站前面有文章介绍了如何实现发表微博说说:PHP+Mysql+jQuery实现发布微博程序--jQuery篇,本例将基于其数据库结构,用动态的方式展示发表的说说信息。 查看示例:DE...

新安装的MySQL数据库需要注意的安全知识

在Unix(Linux)上,在按照手册的指令安装好MySQL后,你必须运行mysql_install_db脚本建立包含授权 表的mysql数据库和初始权限。在Windows上,运行分发中...

PHP MYSQL实现登陆和模糊查询两大功能

PHP MYSQL实现登陆和模糊查询两大功能

本文使用的软件版本如下:PHP版本 5.5.12;MYSQL版本 5.6.17;Apache 2.4.9 用的wampserver 一、PHPMYSQL实现登陆 一共含有两个文件:log...