简体   繁体   中英

In a transaction. Do I need to rollback at every fail? or exiting the script without commit is enough?

suppose I have this code

 $transactionfailed = false;
 $mysqliconn->query("begin;");
 //query 1
 $result=$mysqliconn->query("insert into table(col1,col2) values('$val1','val2')");
 if(!$result){$transactionfailed=true;}
 //query 2
 $result=$mysqliconn->query("insert into table2(col1,col2) values('$val1','val2')");
 if(!$result){$transactionfailed=true;}
 if($transactionfailed){$mysqliconn->query("rollback;");}
 else{$mysqliconn->query("commit;");}
 die();

I want to replace it with this one

 $mysqliconn->query("begin;");
 //query 1
 $result=$mysqliconn->query("insert into table(col1,col2) values('$val1','val2')");
 if(!$result){die("error");}
 //query 2
 $result=$mysqliconn->query("insert into table2(col1,col2) values('$val1','val2')");
 if(!$result){die("error");}
 $mysqliconn->query("commit;");
 die();

I want to end the script if something wrong happened without rolling back or committing, depending on mysql database to roll back the transaction if I didn't commit it.

I tried it many times, and yes it do rollback the transaction if I exit without commit. but is this always SAFE ? . or there is something I miss. because I don't want that query2 is failed and query1 is committed one day later.

I suggest using try/catch blocks,
put 'begin' query before try block
put your 'insert' queries in the try block
put your 'rollback' query in the catch block
if no query failed in the try block 'commit' once lastly in the try block
if any query failed in the try block 'rollback' once in the catch block (all queries after the begin query will be rolled back)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM