How do you get a complete log of the SQL queries done when a request is made? You could use a plugin for that, but sometimes it may be easier to a few lines of code and after the job is done, remove them.
In my case, I needed to know where some data, that comes from a custom options panel, in a third-party plugin, is saved. It was hard to find it in the code. So I ended up with a log of the SQL queries. Then I searched for UPDATE
queries and found the table that was affected. That way I was able to find it and after that could create my own function that would use that data.
First of all, we need to define a constant that will force WordPress to save all queries.
Add the following code in wp-config.php
define('SAVEQUERIES', true);
Next, we need to save them somewhere. I’ll instruct it to save them in a file under the uploads
folder. I choose uploads
it because it already should be writable by WP.
Add the following code in the functions.php
file of your active theme or in a custom plugin.
add_action('shutdown', 'mySqlLogger');
function mySqlLogger()
{
global $wpdb;
$file = fopen(trailingslashit(WP_CONTENT_DIR) . 'uploads/sqlLogs.txt', 'a');
fwrite($file, "\n\n------ NEW REQUEST [" . date("F j, Y, g:i:s a") . "] ------\n\n");
foreach ($wpdb->queries as $q) {
fwrite($file, $q[0] . " - ($q[1] s)" . "\n\n");
}
fclose($file);
}
Now if you reload a page, make an ajax request, or save something, all SQL requests will be saved in uploads/sqlLogs.txt
Simple like that!
Warning! Once you’ve found what you needed, make sure to remove this code from your theme/plugin. This should never run in a production environment. It’s intended only for development purposes.
Hi there. Thanks so much for the article and the sample code. Is there a way to log only any change on a specific table instead to avoid any performance impact?
Thanks again!
Hi. You must focus on the foreach loop and check what type of request you have then save it or not. Here’s and example that looks for queries that modify the data:
I haven’t tested it, but theoretically it must log the queries only if they are one of INSERT, UPDATE or DELETE