[php] How do I check if PHP is connected to a database already?

Basically in pseudo code I'm looking for something like

if (connected_to_any_database()) {
    // do nothing
}
else {
    mysql_connect(...)
}

How do I implement

connected_to_any_database()

This question is related to php mysql

The answer is


before... (I mean somewhere in some other file you're not sure you've included)

$db = mysql_connect()

later...

if (is_resource($db)) {
// connected
} else {
$db = mysql_connect();
}

Try using PHP's mysql_ping function:

echo @mysql_ping() ? 'true' : 'false';

You will need to prepend the "@" to suppose the MySQL Warnings you'll get for running this function without being connected to a database.

There are other ways as well, but it depends on the code that you're using.


// Earlier in your code
mysql_connect();
set_a_flag_that_db_is_connected();

// Later....
if (flag_is_set())
 mysql_connect(....);

Baron Schwartz blogs that due to race conditions, this 'check before write' is a bad practice. He advocates a try/catch pattern with a reconnect in the catch. Here is the pseudo code he recommends:

function query_database(connection, sql, retries=1)
   while true
      try
         result=connection.execute(sql)
         return result
      catch InactiveConnectionException e
         if retries > 0 then
            retries = retries - 1
            connection.reconnect()
         else
            throw e
         end
      end
   end
end

Here is his full blog: https://www.percona.com/blog/2010/05/05/checking-for-a-live-database-connection-considered-harmful/