Print

MySQL Transactions in PHP

Sometimes it is critical to ensure a group of queries are all executed successfully to maintain the integrity of our data. Let's say we have a banking app where we need to subtract funds from one account and add funds to another:

copyraw
$mysqli->query ("UPDATE 'accounts' SET 'balance' = 'balance'-1000000 WHERE 'user' = 'Bob'");
$mysqli->query ("UPDATE 'accounts' SET 'balance' = 'balance'+1000000 WHERE 'user' = 'Fred'");
  1.  $mysqli->query ("UPDATE 'accounts' SET 'balance' = 'balance'-1000000 WHERE 'user' = 'Bob'")
  2.  $mysqli->query ("UPDATE 'accounts' SET 'balance' = 'balance'+1000000 WHERE 'user' = 'Fred'")

What if one of the queries fails? To mitigate the chances of misplacing our millions due to some possible error we must ensure that both queries are executed with the expected result before committing any changes to the data. This where transactions are useful. We can run the queries, then check if some conditions are met before committing the changes in the data:

copyraw
$mysqli->begin_transaction();
$mysqli->query ("UPDATE 'accounts' SET 'balance' = 'balance'-1000000 WHERE 'user' = 'Bob'");
$a1=$mysqli->affected_rows();

$mysqli->query ("UPDATE 'accounts' SET 'balance' = 'balance'+1000000 WHERE 'user' = 'Fred'");
$a2=$mysqli->affected_rows();

//Check 1 row affected by each query
if ($a1==1 && $a2==1) {
	
	//Everything looks OK, commit changes
	$mysqli->commit();
	
} else 

	//Something went wrong. Roll back to before begin_transaction()
	$mysqli->rollback();
}
$mysqli->close();
  1.  $mysqli->begin_transaction()
  2.  $mysqli->query ("UPDATE 'accounts' SET 'balance' = 'balance'-1000000 WHERE 'user' = 'Bob'")
  3.  $a1=$mysqli->affected_rows()
  4.   
  5.  $mysqli->query ("UPDATE 'accounts' SET 'balance' = 'balance'+1000000 WHERE 'user' = 'Fred'")
  6.  $a2=$mysqli->affected_rows()
  7.   
  8.  //Check 1 row affected by each query 
  9.  if ($a1==1 && $a2==1) { 
  10.   
  11.      //Everything looks OK, commit changes 
  12.      $mysqli->commit()
  13.   
  14.  } else 
  15.   
  16.      //Something went wrong. Roll back to before begin_transaction() 
  17.      $mysqli->rollback()
  18.  } 
  19.  $mysqli->close()

mysqli->begin_transaction() requires PHP 5.6 and above. For lower versions you can issue the MySQL commands directly like:

mysqli->query("START TRANSACTION")
mysqli->query("COMMIT")
mysqli->query("ROLLBACK")

Important note: Our tables must use an engine that supports transactions ie. InnoDB. Don't be silly like me and spend hours wondering why your transactions aren't working on MyISAM tables.

Category: MySQL :: Article: 644