What you are after is Transactions
]. You usually begin a transaction and do all the stuff you need to to do: UPDATE, INSERT etc. and only after you're done and everything was successful you do a commit. In case of error at any stage in the process you do a rollback and everything looks as if you had never touched it.
Here another source that explaind Commit and Rollback: What is commit and rollback?