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

前端 未结 6 2343
误落风尘
误落风尘 2020-12-09 14:29

Basically in pseudo code I\'m looking for something like

if (connected_to_any_database()) {
    // do nothing
}
else {
    mysql_connect(...)
}
相关标签:
6条回答
  • 2020-12-09 15:16

    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/

    0 讨论(0)
  • 2020-12-09 15:23

    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();
    }
    
    0 讨论(0)
  • 2020-12-09 15:28

    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.

    0 讨论(0)
  • 2020-12-09 15:29
    // Earlier in your code
    mysql_connect();
    set_a_flag_that_db_is_connected();
    
    // Later....
    if (flag_is_set())
     mysql_connect(....);
    
    0 讨论(0)
  • 2020-12-09 15:31

    mysql_ping

    0 讨论(0)
  • 2020-12-09 15:35

    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
    }
    
    0 讨论(0)
提交回复
热议问题