简体   繁体   中英

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()

Have you tried mysql_ping() ?

Update: From PHP 5.5 onwards, use mysqli_ping() instead.

Pings a server connection, or tries to reconnect if the connection has gone down.

 if ($mysqli->ping()) { printf ("Our connection is ok!\\n"); } else { printf ("Error: %s\\n", $mysqli->error); }

Alternatively, a second (less reliable) approach would be:

$link = mysql_connect('localhost','username','password');
//(...)
if($link == false){
    //try to reconnect
}

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.

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();
}

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/

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

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

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