Debug wpdb database queries in a WordPress Plugin or Theme

By | July 13, 2016

Today one of my own developed plugin stopped working! It was doing a very basic job of collecting some data from users and inserting it into a WordPress database and finally sending the response email to the user as well as the site admin about the successful transaction.

As it stopped functioning, I had to put the debug option ON to find out the exact reason. It was easy to find out that the error was not in PHP but the MySQL/$wpdb query was failing. But as there was no PHP error, the setting of WP_DEBUG as TRUE in wp-config.php (for either displaying the errors on the screen or writing them to a log file), did not work. My need was to display or log the error after the database insert query was executed.

The below code worked for me in debugging the $wpdb i.e. WordPress database queries:

global $wpdb;
$wpdb->show_errors(); //setting the Show or Display errors option to true
$wpdb->insert(...... //your $wpdb query

In case, if you do not want to display the errors on screen, but log them in debug.log file residing in your wp-content folder, you need to edit the wp-config.php file and add the below constants:

define( 'WP_DEBUG', true ); //this should always be added to display errors on the screen or log the errors in the log file
define( 'WP_DEBUG_LOG', true );
define( 'WP_DEBUG_DISPLAY', false );

My site was a WordPress multisite i.e. WordPress Network installation, so I had to add one extra constant to wp-config.php file as

define( 'DIEONDBERROR', true );

In case you need to review or analyze all the queries while executing a particular code or displaying the page, you can save the queries in a global array viz. $wpdb->queries. In order to save the queries in this array, you need to add one more constant in the wp-config.php file as follows:

define( 'SAVEQUERIES', true );

You can display this array anywhere in your flow of execution as

global $wpdb;
print_r( $wpdb->queries );

Make sure you turn OFF all the debugging configuration and displays once you are done with the debugging. Keeping them ON may cost you on the site performance resulting in slower page load and unnecessary server utilization.