// Connect to database $conn = mysqli_connect("localhost", "user", "password", "database"); // Start transaction mysqli_begin_transaction($conn); // Execute SQL statements mysqli_query($conn, "INSERT INTO users (name, email) VALUES ('John', 'john@example.com')"); mysqli_query($conn, "INSERT INTO users (name, email) VALUES ('Jane', 'jane@example.com')"); // Commit transaction mysqli_commit($conn);
// Connect to database $conn = mysqli_connect("localhost", "user", "password", "database"); // Start transaction mysqli_begin_transaction($conn); try { // Execute SQL statements mysqli_query($conn, "INSERT INTO users (name, email) VALUES ('John', 'john@example.com')"); mysqli_query($conn, "INSERT INTO users (name, email) VALUES ('Jane', 'jane@example.com')"); // Trigger an error throw new Exception("Rolled back transaction"); // Commit transaction mysqli_commit($conn); } catch (Exception $e) { // Roll back transaction mysqli_rollback($conn); }In the above example, we have connected to a database and started a transaction using `mysqli_begin_transaction` method. We have then executed two SQL statements to insert data into a table. We have intentionally triggered an error to show how to roll back a transaction. We have caught the error and rolled back the transaction using `mysqli_rollback` method. Package Library: MySQLi