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?
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.
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.
$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