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');
?>
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?