Wordpress - How to print the excuted sql right after its execution

The $wpdb object has some properties getting set for that:

global $wpdb;

// Print last SQL query string
echo $wpdb->last_query;

// Print last SQL query result
echo $wpdb->last_result;

// Print last SQL query Error
echo $wpdb->last_error;

Note: First of all you have to set define( 'SAVEQUERIES', true ); in your wp-config.php file at root folder of WordPress.


I've listed down 3 approaches in here:

  1. Using SAVEQUERIES and printing all the queries in footer
  2. Using $wpdb->last_query to print just the latest query executed, this is useful for debugging functions.
  3. Using a plugin like Query Monitor.

You'd need to add this in your wp-config.php

 define('SAVEQUERIES', true);

Then in the footer of your theme add this code:

 <?php
  if (current_user_can('administrator')){
   global $wpdb;
   echo "<pre>Query List:";
   print_r($wpdb->queries);
   echo "</pre>";
 }//Lists all the queries executed on your page
?>

Or if you'd like to print just the last executed query, you can use this just below your $wpdb query function call.

global $wpdb;
echo $wpdb->last_query;//lists only single query

A 3rd approach would be to use a plugin like Query Monitor which lists all the queries executed on a page in detail, and other details associated with it like how many rows it returns and the time taken for execution or if it's a slow query. http://wordpress.org/plugins/query-monitor/

It's a good idea to use this plugin in DEV environment only and shouldn't be left activated on a live site. Also, Query Monitor can sometimes cause issues with your page, Like 5XX error on your template/page if there are too many errors.


You have to add both functions,otherwise it will never show error

$wpdb->show_errors(); 
$wpdb->print_error();

This function will show you proper error like this this

enter image description here

Tags:

Wpdb

Wp Query