closing a database handle

Go To StackoverFlow.com

0

I have a generic function that closes connections and it takes a dbh, the currently open database handle by ref.

I call it like this

closeconnection($dbh)

depending on the case whether this dbh was a sqlsrv dbh or a mysql dbh, I do one of the two things;

sqlsrv_close( $dbh);

or

mysql_close($dbh);

Short of passing the connection type in the function call, is there a way to find out whether this is a mysql or mssql handle programmatically by simply probing the $dbh which was passed by ref?

2012-04-03 20:53
by Average Joe
Short is putting it at application-wide scope - Alexander 2012-04-03 20:57
Why not use PDO? There are both mysql and sqlsrv drivers for PDO, using PDO for both DB types will give you a unified interface to the DBMS and you can close the connection by simply unsetting the instance - GordonM 2012-04-03 21:38


1

Try using get_resource_type($dbh);. It'll return mysql link for a MySQL DB handle. I don't know what it will return for anything else as MySQL is all I have handy.

2012-04-03 21:04
by Crontab
Thanks Crontab, it returns "SQL Server Connection" - Average Joe 2012-04-03 23:49


2

A way using an application-wide could be defining an interface.

// connection interface
interface db
{
  public function close($conn);
}

Providing implementations for the used drivers.

// mysql
class mysql implements db
{
  public function close($conn) { 
    mysql_close($conn);
  }
}
// mssql
class mssql implements db {
  public function close($conn) {
    sqlsrv_close($conn);
  }
}

Using an application-wide variable to instantiate the proper driver.

if($driver == "mysql") {
  $db = new mysql();
} elseif($driver == "mssql") {
  $db = new mssql();
}
...
$db::close($conn);

This is like the most common way to handle it.

Also as anyone will recommend you, you should use start using PDO to tackle this.

2012-04-03 21:07
by Alexander
thank you Alexander but the whole point of the question was how to get the $driver being mysql or not... crontab addressed it. thank you for your time. I'm new to PHP. What's a good resource you can recommend about the interface and learning when and when not to use it - Average Joe 2012-04-03 22:15
You already know what $driver is, you are simply choosing to forget it ;). Simply read about OOP to learn about interface and related - Alexander 2012-04-03 22:17
Ads