When should you use ROLLBACK?

In MySQL, ROLLBACK is used to undo changes made during the current transaction. It is essential to use ROLLBACK when you encounter an error during a transaction or when you need to ensure data integrity upon certain conditions not being met. By reverting to the last committed state, ROLLBACK helps maintain consistent data in your database.

For example, if you are transferring money between two accounts, you want to ensure that either both the debit and credit operations succeed, or neither do. If the credit operation fails after the debit operation, you would use ROLLBACK to revert the debit operation and avoid losing money.

// Start transaction mysqli_query($conn, 'START TRANSACTION'); // Perform operations mysqli_query($conn, 'UPDATE accounts SET balance = balance - 100 WHERE account_id = 1'); // Check for errors if (mysqli_affected_rows($conn) < 0) { // Rollback if needed mysqli_query($conn, 'ROLLBACK'); die('Transaction failed'); } // Commit if successful mysqli_query($conn, 'COMMIT'); ?>

ROLLBACK MySQL database transactions data integrity error handling SQL transactions