-
Notifications
You must be signed in to change notification settings - Fork 37
TransactionHandler
hooman helmi edited this page Jun 2, 2025
·
2 revisions
The TransactionHandler class manages MySQL transactions using WordPress's $wpdb instance.
It ensures that operations either complete fully or roll back entirely on failure, maintaining database consistency during critical operations like schema changes or data migrations.
use WP_Statistics\Service\Database\Managers\TransactionHandler;
global $wpdb;
// Create a transaction handler using the global $wpdb instance.
$transactionHandler = new TransactionHandler($wpdb);// Start a new transaction.
$transactionHandler->beginTransaction();// Commit the current transaction.
$transactionHandler->commitTransaction();// Rollback all operations since the last beginTransaction().
$transactionHandler->rollbackTransaction();use WP_Statistics\Service\Database\Managers\TransactionHandler;
global $wpdb;
$transactionHandler = new TransactionHandler($wpdb);
// Perform multiple queries safely within a transaction.
$transactionHandler->executeInTransaction(function () use ($wpdb) {
// Safe multi-step DB operation
$wpdb->insert('wp_statistics_sample', [
'name' => 'entry1',
'count' => 1,
]);
$wpdb->update('wp_statistics_sample', [
'count' => 2
], [
'name' => 'entry1'
]);
});use WP_Statistics\Service\Database\Managers\TransactionHandler;
global $wpdb;
// Instantiate the transaction handler
$transactionHandler = new TransactionHandler($wpdb);
try {
// Begin the transaction manually
$transactionHandler->beginTransaction();
// Run one or more SQL operations
$wpdb->insert('wp_statistics_sample', [
'name' => 'test',
'count' => 1,
]);
$wpdb->update('wp_statistics_sample', [
'count' => 2,
], [
'name' => 'test',
]);
// Commit changes if all operations succeed
$transactionHandler->commitTransaction();
} catch (\Exception $e) {
// If anything fails, rollback all operations
$transactionHandler->rollbackTransaction();
// Optional: log or throw the error
error_log('Transaction failed: ' . $e->getMessage());
}-
Transaction State: Internal transaction state is tracked and resets after each
commitorrollback. - Autocommit Handling: The class ensures autocommit mode is properly set before and after transactions, providing safe and predictable behavior.