开发者

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

开发者 https://www.devze.com 2023-02-14 04:08 出处:网络
Basically in pseudo code I\'m looking for something like if (connected_to_any_database()) { // do nothing

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.


mysql_ping


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(....);
0

精彩评论

暂无评论...
验证码 换一张
取 消