How To Print The Executed SQL Query in WordPress

Share this Article
Reading Time: 4 minutes
356 Views

Inside this article we will see the concept of printing executed SQL query in wordpress. In several cases we want to print the executed sql query, print result set data of wordpress.

If you are looking for an article i.e How to print the executed sql query in wordpress then you are at right place to get the things. This article contains classfied information which gives you the prefect idea to learn and run your queries.


Premium Courses Running Out, Grab Now!

Master the Coding Skills to Become an Expert in Web Development. A lifetime of knowledge at your fingertips.

Enroll in your favourite web development courses risk-free at $4 only.


Learn More –

Let’s get started.


What is WordPress Core Database Class?

WordPress manages almost 99% data via it’s database. Database is one of the major part of wordpress which when lost or destroyed then site will be crashed. There are 10000+ of plugins available free at wordpress repository to get any type of data from site database.

WordPress database object comes into play. It is global which can use anywhere by calling it’s methods.

To perform any database operations, WordPress provides a class called wpdb which is present in the directory at core libraries wordpress folder /wp-includes and file is /wp-includes/wp-db.php

The class “wpdb” abstracts the wordpress database functions. Most of the WordPress functions directly or indirectly use wpdb class. WordPress class wpdb based on the concept ezSQL class.

We can create an object of this wpdb class and perform all database operations but wordpress auto creates an object of this class while wordpress loads.

global $wpdb;

Print Executed SQL in WordPress

To print sql queries in wordpress we use $wpdb object. The $wpdb object has some properties for this.

There are few easy steps to do so –

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

We need to add this in wp-config.php

define('SAVEQUERIES', true);

Using $wpdb properties to debug queries

  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;

We hope this article helped you to learn How To Print The Executed SQL Query in WordPress Tutorial in a very detailed way.

Buy Me a Coffee

If you liked this article, then please subscribe to our YouTube Channel for PHP & it’s framework, WordPress, Node Js video tutorials. You can also find us on Twitter and Facebook.