Junior — Middle
What is the necessity of using transactions when working with databases?
sobes.tech AI
Answer from AI
Transactions in databases are necessary to ensure the integrity and consistency of data when executing multiple related operations. They guarantee that either all operations within a transaction are successfully completed, or none are applied (atomicity). This is important to avoid partial data updates, which can lead to errors and inconsistency.
The main properties of transactions (ACID):
- Atomicity — all operations of a transaction are executed as a single unit.
- Consistency — after a transaction, the database remains in a correct state.
- Isolation — parallel transactions do not affect each other.
- Durability — changes committed by a transaction are saved even in case of failures.
Example in PHP using PDO:
$pdo->beginTransaction();
try {
$pdo->exec("INSERT INTO accounts (user_id, balance) VALUES (1, 1000)");
$pdo->exec("UPDATE accounts SET balance = balance - 100 WHERE user_id = 2");
$pdo->commit();
} catch (Exception $e) {
$pdo->rollBack();
echo "Error: " . $e->getMessage();
}
Here, if one of the operations fails, changes will not be saved, preventing data inconsistency.