Re-using your database connection in PHP

Often I've wondered what'd be the best practice when connecting to MySQL with PHP. Many people use some function and possibly open and close their database connection multiple times. Well, I've used global variables and such to keep track of the connection, but often global variables do not behave well in include files. Anyways, to get your code structured even better, you'd probably like everything to be in a class.

Solution: In PHP 5 we have static variables. So you simply use a static variable for your connection and make sure it isn't opened more than once. PHP will take care of closing it again. In that way you can always by accident create too many instances of your database class - which you're very likely to have since many components are gonna want database access independent of each other.

By the way, in the example the example I also use the very usable __autoload() function.

In short, here's the code:

Some file:

require_once('../lib/autoload.php');
$my_conn = new MyDB();
$my_conn = new MyDB();

?>

mydb.class.php:

/ Default Database connection parms /

$db_host = 'localhost';
$db_user = 'xxx';

$db_pass = 'xxx';
$db_name = 'xxx';

class MyDB {

static $connection;

function __construct ( $host=NULL, $user=NULL, $pass=NULL, $name=NULL ) {

if ( !isset(self::$connection) ) {

if ( $host == NULL ) {

$host = $db_host;

$user = $db_user;

$pass = $db_pass;

$name = $db_name;

}

self::$connection = mysql_connect( $host, $user, $pass, $name );

if (!self::$connection)

$this->print_error ('Could not connect to database!');

} else {

echo "Warning: Connection is already established!
";

}

}

public function print_error ( $my_msg ) {

echo "<b>Database error!</b>
$my_msg
" . mysql_error();

}

}

?>

...will output:

Warning: Connection is already established!

A quick note: PHP's mysql_connect() already keeps track of connections to avoid opening the same connection multiple times. So why this approach? Well, suppose that you left it all up to PHP: Then you wouldn't be in control anymore, and different pieces of code utilizing the same MySql functions would be impossible to keep track of. That's the reason for static properties and methods - to make something shared across multiple instances.