Php+mysql method of realizing transfer function based on transaction processing _php skills

Source: Internet
Author: User

The examples in this article describe the Php+mysql method for implementing the transfer function based on transaction processing. Share to everyone for your reference. as follows:

<?php header ("Content-type:text/html;charset=utf-8");
  $mysqli =new mysqli ("localhost", "root", "" "," Test ");
  if (Mysqli_connect_errno ()) {printf ("Connection Failed:%s<br>", Mysqli_connect_error ());
  Exit ();
  } $success =true;
  $price = 8000;
  $result = $mysqli->query ("Select cash from the 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 ' balance is insufficient ';
  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 ' Transfer succeeded! ';
  }else {$mysqli->rollback ();
  echo "Transfer failed!";
  } $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 "User UserA value is:". $cash;

 $mysqli->close ();?>

The database SQL statement is as follows:

CREATE TABLE account{
 userID smallint unsigned NOT null auto_increment,
 name varchar (=) NOT null,
 cash DECIM Al (9,2) not NULL,
 primary KEY (UserID)
) Type=innodb;
Insert into account (Name,cash) VALUES (' UserA ', ' n ');
Insert into account (Name,cash) VALUES (' UserB ', ' 10000 ');

I hope this article will help you with your PHP program design.

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.