Skip to content

Instantly share code, notes, and snippets.

@nciske
Forked from 5iDS/wpdb-transactions
Last active April 24, 2022 13:45
Show Gist options
  • Star 9 You must be signed in to star a gist
  • Fork 5 You must be signed in to fork a gist
  • Save nciske/3b6b6367fdb5fa0dd26e91042b4ea309 to your computer and use it in GitHub Desktop.
Save nciske/3b6b6367fdb5fa0dd26e91042b4ea309 to your computer and use it in GitHub Desktop.
MySQL database transaction, using the WordPress database object $wpdb. Requires the InnoDB table format.
<?php
global $wpdb;
// Start Transaction
$wpdb->query( "START TRANSACTION" );
// Do some expensive/related queries here
//$wpdb->query("DELETE FROM table WHERE form_id = '1' ");
//$wpdb->query("DELETE FROM data WHERE form_id = '1' ");
// set $error variable value in error handling after $wpdb modifications
if ($error) {
// Error occured, don't save any changes
$wpdb->query( "ROLLBACK" );
} else {
// All ok, save the changes
$wpdb->query( "COMMIT" );
}
?>
@tedmasterweb
Copy link

Nice. Could you provide an example of how to do this below?

set $error variable value in error handling after $wpdb modifications

TIA

@adrianosferreira
Copy link

adrianosferreira commented Apr 4, 2020

You don't need this check if ($error) {. The $wpdb->query( "COMMIT" ); will automatically calls ROLLBACK in case some command inside the transactions will fail.

So code can be:

<?php
global $wpdb;
 
// Start Transaction
$wpdb->query( "START TRANSACTION" );
 
// Do some expensive/related queries here
//$wpdb->query("DELETE FROM table WHERE form_id = '1' ");
//$wpdb->query("DELETE FROM data WHERE form_id = '1' ");
// set $error variable value in error handling after $wpdb modifications
 
$wpdb->query( "COMMIT" );
?>

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment