<?php //连接数据库 $pdo = new PDO('mysql:host=localhost;dbname=system', "root", ''); //开启事务 $pdo->beginTransaction(); //购买数量 $buynum = $_GET['buynum']; //产品id $productid = $_GET['productid']; //根据购买数量 ,更新库存SQL $re1 = $pdo->exec("update product set libnum = libnum-{$buynum} where id=" . $productid); //根据商品的id,获取商品的信息SQL $sql = "select * from product where id=" . $productid; //执行获取商品信息SQL语句 $pdoS = $pdo->query($sql); //得出一维数组结果 $arr = $pdoS->fetch(PDO::FETCH_ASSOC); //从信息中获取商品单价 $price = $arr['price']; //用户id $userid = $_GET['userid']; //应付金额 (单价*购买数量) $money = $price * $buynum; //更新用户表里的余额语句 $sql = "update user set money=money-{$money} where id = {$userid}"; //执行扣钱语句 $re = $pdo->exec($sql); //如果 库存和余额条件成立 if ($re && $re1) { //开启事务 $pdo->commit(); echo "购买成功"; } else { //回滚 $pdo->rollback(); echo "购买失败"; }