0

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);
Anna
  • 135
  • 9
  • 1
    Have a read of https://stackoverflow.com/a/63764001/1213708 which gives a lot more details. – Nigel Ren Aug 01 '21 at 17:17
  • I have read that one and it didn't answer my question - I'm looking for clarification on whether using both is redundant or if my checks are unnecessary. This is not a duplication question!! That question didn't even discuss whether to perform checks before committing. – Anna Aug 01 '21 at 17:36
  • Something as simple as `If you turn autocommit off, you decide when you want to commit` answers if you should perform checks before a commit. You also need to look at how you configure your connection - `mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);` will automatically fail if a SQL error occurs. Otherwise only you can decide if the data is in a state to be commited. – Nigel Ren Aug 01 '21 at 17:40
  • *"whether using both is redundant"* Why wouldn't it be redundant? Everything is clearly explained in my answer. I said "*You can either switch autocommit off or use a one-time-only transaction.*" which explain the difference between the two modes. – Dharman Aug 01 '21 at 17:45
  • I'm sorry, I guess I just simply don't understand then. As it stands everything is running, but still returning false. The answer given just doesn't make sense to me I guess. – Anna Aug 01 '21 at 17:48

0 Answers0