Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP: How to determine if a database connection is open [duplicate]

Tags:

php

mysql

I have the following class method -

class Someclass
{
    /* Other properties and methods */

    public function close_connection($connection=NULL)
    {
        return mysql_close($connection)
    }
}

Now, before calling the mysql_close function in the above code, I want to check if the $connection points to a open database connection. That is, I want to be sure that the connection I am closing is open and has not already been closed.

How can I do that?

like image 703
MD Sayem Ahmed Avatar asked Jun 19 '10 10:06

MD Sayem Ahmed


3 Answers

You could try checking if your $connection variable is infact a valid resource.

<?php
if(is_resource($connection))
{
    mysql_close($connection);
}
?>

Edit: Okay, this updated code now includes Gordon's suggestion.

<?php
if(is_resource($connection) && get_resource_type($connection) === 'mysql link')
{
    return mysql_close($connection);
}
else
{
    return false;
}
?>
like image 131
user353297 Avatar answered Oct 20 '22 12:10

user353297


You could try mysql_thread_id($connection). That'll return false if there's no usable connection.

like image 24
Travis Avatar answered Oct 20 '22 13:10

Travis


If you have other code that could be closing the connection, have them set the connection to null so you can test for that.

If you are unsure wether the connection has been closed from the other end, due to a timeout or a network error, the only way to test it is to actually send data through using something like mysql_ping. However, this would be a terrible waste of resources if you are just trying to avoid closing a connection that might already be closed.

Note: as mentioned by evord, using mysql_ping will attempt to reopen the connection if it is no longer open.

like image 38
kasperjj Avatar answered Oct 20 '22 14:10

kasperjj