Jump to content
Sign in to follow this  

Php - Mysqli : Transactions

Recommended Posts

I have many select insert update query , i have written transaction query but want to know if its safe or some need to be corrected.


Also if all is ok i should get successful "Transaction completed successfully!" , but if something get wrong then error message showed be seen and ROLLBACK should be done , but its NOT .... not rollback is done


Below is what I have tried. Please let me know if something is wrong:

function autocommitfalse(){global $db;return mysqli_autocommit($db, FALSE);}function autocommittrue(){global $db;return mysqli_autocommit($db, TRUE);}function commitquery(){global $db;return mysqli_commit($db);}function rollbackedquery(){global $db;return mysqli_rollback($db);}


try {global $db;autocommitfalse();-----------------$SQLSELECT = "SELECT * FROM BC ";$result_as = mysqli_query($db,$SQLSELECT);$rsfetch = mysql_fetch_array($result_as);if(!$result_as ){throw new Exception('Wrong SQL SELECT: ' . $SQLSELECT. ' Error: '.db_error_msg($db) . db_error_no());}-----------------$sqla ="INSERT INTO A (sd) VALUES ('df') where id=".$rsfetch['dh'];$result_a = mysqli_query($db,$sqla);if(!$result_a){throw new Exception('Wrong SQL SELECT: ' . $result_a. ' Error: '.db_error_msg($db) . db_error_no());}-----------------$sqlb ="INSERT INTO B (sdds) VALUES ('trtrt') where id=".$rsfetch['dh'];$result_b =mysqli_query($db,$sqlb);if(!$result_{throw new Exception('Wrong SQL SELECT: ' . $result_a. ' Error: '.db_error_msg($db) . db_error_no());}-----------------$a = mysqli_insert_id($db);-----------------$sqlCb ="UPDATE CB SET A ='NM' where id=".$a ;$result_Cb = mysqli_query($db,$sqlCb);if($result_Cb === false || mysqli_affected_rows($db) == 0 ){throw new Exception('Wrong SQL SELECT: ' . $result_a. ' Error: '.db_error_msg($db) . db_error_no());}-----------------commitquery();echo 'Transaction completed successfully!';} catch (Exception $e) {echo"<br >";echo "<table align=center><tr><td>";echo $e->getMessage();echo "</td></tr></table>";echo"<br >";echo display_error(_("Transaction failed: transaction rolled back"));rollbackedquery();}autocommittrue();

Please let me know its correct or not , if need to correct then what , as still not rollbacked with above code..

Edited by shashib

Share this post

Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Sign in to follow this  

  • Create New...