I am not new to php/mysqli coding, but I have never actually used a transaction before. I have found conflicting information on how to properly start and execute the transaction. I've seen some people use autocommit(false)
, others only use begin_transaction();
, others have said to only commit after running checks, but others have said that commit WON'T run if there are errors... I'm truly confused as to what the proper syntax is. Any help is appreciated!
//turn autocommit off and start transaction
$mysqli->autocommit(false);
$mysqli->begin_transaction();
//declare queries and make sure they all run properly
$result1 = $mysqli->query(myqueryhere);
if(!$result1) { $error[] = true; }
$result2 = $mysqli->query(mysecondqueryhere);
if(!$result2) { $error[] = true; }
$result3 = $mysqli->query(mythirdqueryhere);
if(!$result3) { $error[] = true; }
//only commit if there are no errors
if(empty($error)) {
$mysqli->commit();
}
//turn autocommit back on for future queries
$mysqli->autocommit(true);