PHP: Checking to see if a MySQL connection exists.

The other day, I was in need of a quick and dirty script that would log the total number of MySQL queries that a specific page was running. i.e. If one of the pages on our app was running 40+ MySQL queries per request, I wanted to know about it.

The problem was:

  • This application has thousands of pages. There was no way that I was going to edit each file in a separate fashion.
  • I could not make the assumption every page was creating a MySQL connection (some weren’t).

My first course of action was to create a script called post.inc.php. I then added the path to this script to the auto_append_file directive in my php.ini file. This directive allows you to specify a script that will be automatically included by all PHP files. Simply put, this directive tells PHP to automatically include post.inc.php at the end of every script.

Because the app in question uses the dreaded mysql_* functions, I was forced to use a function called mysql_thread_id. Example code:

<?php

if(@mysql_thread_id() !== false){
    //A MySQL connection exists.
    //Do something.
} else{
    //Connection does not exist.
}

As you can see, it’s actually pretty simple. A few notes about this particular approach:

  • The @ operator is used to suppress the E_WARNING error that will occur if a connection does not exist. Typically, you should avoid this kind of thing. However, this is a dirty ad-hoc script, so I think we can forgive ourselves.
  • I used mysql_thread_id instead of mysql_ping because the latter function will attempt to create a new connection if no connection is found (this will only happen if the MySQL version is below 5.0.3. In version >= 5.0.3, this behaviour is disabled).

So, there you go. Hopefully, you found this article useful!