Mysql交易處理(一個轉賬程式)

來源:互聯網
上載者:User
<無詳細內容>
  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');
複製代碼
  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.