//Assuming a valid database connection has been established using $pdo try { $pdo->beginTransaction(); //Run some SQL queries $pdo->commit(); //Saves changes } catch (PDOException $e) { $pdo->rollback(); //Undo all changes made echo "Error: " . $e->getMessage(); //Display a message to the user }
//Assuming a valid database connection has been established using $mysqli $mysqli->autocommit(false); //Start a transaction //Run some SQL query //If errors occur, use $mysqli->rollback(); $mysqli->commit(); //Saves changes $mysqli->autocommit(true); //End transactionIn this example, we use the mysqli library to execute a SQL query within a transaction. Before beginning the transaction, we disable autocommit mode with `$mysqli->autocommit(false)`. If no errors occur, we use `$mysqli->commit()` to save changes before re-enabling autocommit mode with `$mysqli->autocommit(true)`. In both examples, we use package libraries to access and manipulate databases in PHP. In the first example, we use the PDO library, while in the second example, we use the mysqli library. Both libraries allow us to connect to databases, execute queries, and handle transactions.