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?
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;
}
?>
You could try mysql_thread_id($connection). That'll return false if there's no usable connection.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With