PHP Transaction Instance Resolution Using Mysql

  • 2021-07-18 07:18:01
  • OfStack

This article illustrates an example of PHP using MySQL, and has a note to explain it in detail. Share it with you for your reference.

Specific examples are as follows:


<?php
// Database connection 
$conn = mysql_connect('localhost', 'root', '');
mysql_select_db('test', $conn);
mysql_query("SET NAMES GBK");

/*
 The table that supports transactions must be InnoDB Type 
1 Segment transactions can only appear 1 Times :
mysql_query('START TRANSACTION');// Start a transaction 
mysql_query(' ROLLBACK ');// Rollback transaction 
mysql_query('COMMIT');// Commit transaction 

 If 1 If multiple rollback transactions occur in a segment transaction, when the transaction is committed, only the 1 Cancel all operations on the database from the second rollback to the beginning of the transaction 1 After the second rollback, all operations on the database will still be valid until the transaction is committed, so 1 Put the rollback statement only before the commit transaction statement 
 If 1 If there is no commit statement in a segment transaction, the following operations on the database are executed from the beginning of the transaction (the execution method returns right or wrong), but there is no impact on the database. However, when the next segment starts the transaction statement, the previous transaction is automatically committed 
*/
mysql_query('START TRANSACTION');
$isBad = 0;

$ins_testTable1 = "INSERT INTO testtable1(NAME,age)VALUES('first',23)";
if(!mysql_query($ins_testTable1)){
  $isBad =1;
}
// Insert statement field name incorrect 
$ins_testTable2 = "INSERT INTO testtable1(NAME,ages)VALUES('second','24')";
if(!mysql_query($ins_testTable2)){
  $isBad =1;
}
if($isBad == 1){
  echo $isBad;
  mysql_query('ROLLBACK ');
}
mysql_query('COMMIT');
mysql_close($conn);
?>

I hope the examples described in this paper are helpful to the study of PHP + MySQL programming.


Related articles: