START TRANSACTION is a command in MySQL that initiates a new transaction. A transaction is a sequence of one or more SQL operations that are executed as a single unit. It allows you to execute multiple queries while ensuring that either all the changes are committed to the database or none of them are, maintaining data integrity.
When you begin a transaction with START TRANSACTION, it sets the context for all the subsequent SQL statements until a COMMIT or ROLLBACK command is executed. This is particularly useful for operations that require consistency, such as transferring funds between accounts or updating multiple related records.
In the event of an error or if any single operation within the transaction fails, you can roll back all changes to maintain the database's integrity.
Here’s an example of how START TRANSACTION is used in MySQL:
<?php
// Connect to the database
$conn = new mysqli("localhost", "username", "password", "database");
// Start a transaction
$conn->begin_transaction();
try {
// Perform multiple queries
$conn->query("INSERT INTO accounts (name, balance) VALUES ('Alice', 1000)");
$conn->query("INSERT INTO accounts (name, balance) VALUES ('Bob', 500)");
// Commit the transaction
$conn->commit();
} catch (Exception $e) {
// Rollback the transaction if any query fails
$conn->rollback();
echo "Failed: " . $e->getMessage();
}
// Close the connection
$conn->close();
?>
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?