PHP+MYSQL transaction processing

Keywords: Database PHP Mobile SQL

For PHP + MYSQL transaction processing, first of all, transactions must be supported during database design, so when designing data tables, InnoDB is selected as the database engine. If the database engine selected does not support transactions, such as MyISAM, it can be locked through tables

Here is a simple example of a transaction implementation:

Database name: test;

Data table: person table, phone table;

person table fields: id (primary key), name (name), card (card number), money (balance)

Phone table fields: id (primary key), phone number (mobile number), add money (recharge amount), userID (person table id);

Input the recharge amount in the foreground, and a certain amount of money will be subtracted from the money in the person table, and a recharge record will be added in the phone table

The code is as follows:

<?php
header("Content-Type: text/html; charset=utf-8");

$con=mysqli_connect('localhost','root','root','test');
if (!$con){ 
	apiReturn('0',"Connection error: " . mysqli_connect_error()); 
}
mysqli_set_charset($con,'utf8');
if ($_POST) {
	$name = $_POST['user'];
	$card = $_POST['card'];
	$phone= $_POST['phone'];
	$money= $_POST['money'];
	$sltsql = "select * from person where card=$card and name like " ."'%$name%'";
	$rs = mysqli_query($con,$sltsql);
	while ($rst = mysqli_fetch_assoc($rs)) {
		$money_list = $rst['money']-$money;
		mysqli_query($con,"BEGIN");//Open transaction
		$sql = "INSERT INTO phone VALUES(3,$phone,$money,$rst[id])";
		$sql2 = "UPDATE person SET money =$money_list WHERE id=$rst[id]";
		$res = mysqli_query($con,$sql);
		$res1 = mysqli_query($con,$sql2);
		if($res && $res1){
			mysqli_query($con,"COMMIT");//Submission of affairs
			echo 'Submitted successfully.';
		}else{
			mysqli_query($con,"ROLLBACK");//Transaction rollback
			echo 'Data rollback.';
		}
	}
}
mysqli_query($con,"END");
?>
<html>
	<head>
		<style>
		.main{
		    text-align: center; /*Center the text inside the div*/
		    background-color: #fff;
		    border-radius: 20px;
		    width: 300px;
		    height: 350px;
		    margin: auto;
		    position: absolute;
		    top: 0;
		    left: 0;
		    right: 0;
		    bottom: 0;
		}
		</style>
	</head>
	<body>
	<form action="transaction.php" method="POST">
		<div class="main">
			<div style="width:500px;height: 300px margin:0 auto">
				<span>Full name:<input type="text" name="user" value=""></span><br/><br/>
				<span>Card number:<input type="text" name="card" value=""></span><br/><br/>
				<span>Recharge mobile number:<input type="text" name="phone" value=""></span><br/><br/>
				<span>Recharge amount:<input type="text" name="money" value=""></span><br/>
			</div>
			<br/>
			<div style="width:500px;height: 300px margin:0 auto">
				<span>
					<button type="submit">Submission</button>
				</span>
			</div>
		</div>
		
	</form>		
	</body>
</html>

 

Posted by ceci on Sat, 04 Jan 2020 10:47:28 -0800