What is START TRANSACTION in MySQL?

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(); ?>

START TRANSACTION MySQL transactions SQL operations data integrity COMMIT ROLLBACK