Php+mysqli transaction control to realize _php skills of bank transfer cases

Source: Internet
Author: User
Tags rollback create database

This paper illustrates the method of PHP+MYSQLI transaction control to realize bank transfer. Share to everyone for your reference. The specific analysis is as follows:

Transaction control, which means that all statements are executed successfully before they are committed. Otherwise, if the preceding statement succeeds without succeeding, roll back to the state before execution. This application is illustrated by the case of bank transfers. One account transfer money out, another account must have money to transfer, so that is successful.

The code is as follows:

<?php
//1, CREATE database Connection object
$mysqli = new mysqli ("localhost", "root", "123456", "Liuyan");
if ($mysqli->connect_error) {
 die ($mysqli->connect_error);
}
$mysqli->query ("Set names ' GBK '");

$mysqli->autocommit (false);
First set Autocommit to False, that is, not autocommit

$sql 1 = "Update account set balance=balance-2 where id=1;";
$sql 2 = "Update account set balance=balance+2 where id=2;";
$res 1 = $mysqli->query ($sql 1) or Die ($mysqli->error);
$res 2 = $mysqli->query ($sql 2) or Die ($mysqli->error);

if (! $res 1 | |! $res 2) {
 echo "transfer failure";
 $mysqli->rollback ()//If one is unsuccessful, rollback
}else{
 $mysqli->commit (), and//Two statements are executed successfully, submit
 echo "Transfer succeeded";
}
?>

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.