We are trying to locate a PHP script that is assembling a query and causing havoc. So far we have not succeeded in using grep to locate the script.
Is it possible to use the mySQL pids from show processlist to locate the PHP script issuing the query?
Don’t think so. Much would depend on actual architecture and topology.
Maybe – this, too, might be hugely disruptive, depending on the context – you could attempt to override the mysql_query function (or whatever wrapper is in use among the various scripts) so as to recognize the misbehaving/malicious query and log all relevant information.
See: https://www.php.net/runkit_function_redefine
Since the logging would take place from "inside" the havoc-wreaking script, much more information would be available.
Another possibility could be to filter MySQL queries and induce some recognizable behaviour in the script, like waiting for a long time or throwing an error. This might be doable through MySQL Proxy: https://launchpad.net/mysql-proxy
Assuming the script is malicious, inability to locate it might point to some kind of encryption – and usually such scripts make heavy use of eval(), base64_decode and sometimes gzuncompress(). Looking for these functions might be more productive than searching for the query fragments.
A useful hack, not very useful now, could be to "decorate" queries with revealing comments, such as, "SELECT … WHERE …; — 012345": the "– 012345" part would be ignored by MySQL, but could be easily logged, and grepping "– 012345" would quickly find the target.