简体   繁体   中英

How to show running mysql queries in php

I have an overflow memory usage problem and I need to scan all my scripts.

My question is how can I show a list of running mysql queries in php?

If the problem is on MySQL site this could help a lot:

mysql_query('show processlist');

It should return all queries waiting for processing. I usually use it directly from mysql console where I don't have to format the output.

You can rename the original mysql_query function and write your own containing some additional logging/inspecting code to see what is going wrong with your queries:

rename_function('mysql_query', 'mysql_query_original');
override_function('mysql_query', '$query', 'return mysql_query_override($query);');

function mysql_query_override($query){
    echo "Query started";         // Add some more sensible information here
    $result = mysql_query_original($query);  
    echo "Query ended";           // Add some more sensible information here
    return $result;
}

Unless you are running a site with massive levels of traffic, then any snapshot of the queries running / enqueued is not likely to be representative. There are also problems in terms of correlating the query with the script which spawned it.

I'd recommend instrumenting your own code - use an auto-prepend to define a wrapper around mysql_query() then you can implement your own logging which:

  1. creates a log entry before the script is fired (most log entries are created afterwards - not very handy if the code which writes the log crashes)
  2. records the script which triggered the query and the query itself
  3. records the memory usage before
  4. records the same facts after along with the time taken

Then do a recursive search and replace on your source code to replace calls to mysql_query() with your wrapper function.

I would suggest you connect to your database server and run show full processlist; this will show you all the active queries and you can debug from there. Also, adding some instrumentation to your project to log slow queries would be beneficial.

There is only one query running at any given time, since this is how PHP works, it doesn't do stuff asynchronous. Unless you use some kind of 3rd party library to do it different.

*EDIT: Seems it is possible, maybe take a look at: Asynchronous PHP calls? . However when you get PHP to run async there is still no way to see how many queries are running. Maybe you could try and check some mysql stats while running your code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM