MySQL transaction processing (one transfer program)

Source: Internet
Author: 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 ("Connection failed:%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 ' Insufficient balance ';
  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 ' Transfer succeeded! ';
  35. }else
  36. {
  37. $mysqli->rollback ();
  38. echo "Transfer failed!";
  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 "User UserA value is:". $cash;
  50. $mysqli->close ();
  51. ?>
  52. &&&&&&&&&&&&&&&&&&
  53. CREATE TABLE account{
  54. UserID smallint unsigned NOT NULL auto_increment,
  55. Name varchar () is not NULL,
  56. Cash decimal (9,2) is 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 ');
Copy Code
  • Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    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.