How do I implement transactions in MySQL

Transactions in MySQL are used to ensure data integrity and handling multiple operations as a single unit. A transaction can be committed if all operations are successful or rolled back if any operation fails. Here’s how you can implement transactions in MySQL using PHP:

<?php // Connect to the database $mysqli = new mysqli("localhost", "username", "password", "database"); // Check connection if ($mysqli->connect_error) { die("Connection failed: " . $mysqli->connect_error); } // Start transaction $mysqli->begin_transaction(); try { // Execute the first query $mysqli->query("INSERT INTO users (username, email) VALUES ('user1', 'user1@example.com')"); // Execute the second query $mysqli->query("INSERT INTO orders (user_id, product_id) VALUES (1, 2)"); // Commit transaction $mysqli->commit(); echo "Transaction completed successfully."; } catch (Exception $e) { // Rollback transaction on error $mysqli->rollback(); echo "Transaction failed: " . $e->getMessage(); } // Close connection $mysqli->close(); ?>

MySQL Transactions PHP Data Integrity Database Management