I found a good solution to be a combination of Travis and user353297's (and Gordon's) answers with a little addition of my own:
Old answer (incorrect):
if(is_resource($connection) && get_resource_type($connection) === 'mysql link')
{
if($mysqli_connection_thread = mysqli_thread_id($connection))
{
$connection->kill($mysqli_connection_thread);
}
$connection->close();
}
Edit: I found that the solution I aggregated and used before wasn't actually working properly. This was because I am using mysqli not mysql. My edited answer provides a working version of the previous code but works with the mysqli connection object (which is not, in fact, a resource).
I found the solution here: check if a variable is of type mysqli object?
New answer (and working properly for mysqli):
if(is_object($mysqli_connection) && get_class($mysqli_connection) == 'mysqli')
{
if($mysqli_connection_thread = mysqli_thread_id($connection))
{
$mysqli_connection->kill($mysqli_connection_thread);
}
$mysqli_connection->close();
}
I have created a function containing a few of these statements specific to certain database connections and I call the function at the end of every script once I am sure that I will not be using any of the connections anymore. This makes sure that the threads die, the connection closes - if it is open - and that the resources are freed up, which can become an issue if there are lots of connections to multiple DBs per user, as is my case.
Thanks a lot to Travis, user353297 and Gordon for giving me the info I needed to put this together!