Skip to content

Instantly share code, notes, and snippets.

@radovanx
Forked from 5iDS/wpdb-transactions
Last active August 29, 2015 14:26
Show Gist options
  • Select an option

  • Save radovanx/248f974c2f0c8f0f00d1 to your computer and use it in GitHub Desktop.

Select an option

Save radovanx/248f974c2f0c8f0f00d1 to your computer and use it in GitHub Desktop.
MySQL database transaction, using the WordPress database object $wpdb. When you render a page in WordPress (front end or admin area), the $wpdb database object has already been initialised and opened up a connection to the database. Therefore we can recycle this database connection for our own needs. The $wpdb object saves the database handle as…
<?php
global $wpdb;
// @ prefix used to suppress errors, but you should do your own
// error checking by checking return values from each mysql_query()
// Start Transaction
@mysql_query("BEGIN", $wpdb->dbh);
// Do some expensive/related queries here
$wpdb->query("DELETE FROM table WHERE form_id = '1' ");
$wpdb->query("DELETE FROM data WHERE form_id = '1' ");
if ($error) {
// Error occured, don't save any changes
@mysql_query("ROLLBACK", $wpdb->dbh);
} else {
// All ok, save the changes
@mysql_query("COMMIT", $wpdb->dbh);
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment