Use mysql_pconnect
, that will do what you want.
First, when connecting, the function would first try to find a (persistent) link that's already open with the same host, username and password. If one is found, an identifier for it will be returned instead of opening a new connection.
You could also use a static or singleton class to handle connection pooling for you.
<?php
class dbConnectionPooler
{
static var $connections = array();
private static function createConnection($host, $username, $password, $db) {
$connection = mysql_pconnect($host, $username, $password);
if (FALSE !== $connection) {
$result = mysql_select_db($db, $connection);
if (FALSE !== $result) {
self::$connections[self::getConnectionHash($host, $username, $password, $db)] = $connection;
return $connection;
}
}
}
private static function getConnectionHash($host, $username, $password, $db) {
return md5($host. $username. $password. $db); // use your favourite hashing function here
}
public static function getConnection($host, $username, $password, $db) {
$connectionHash = self::getConnectionHash($host, $username, $password, $db);
if (array_key_exists($connectionHash, self::$connections)) {
return self::$connections[$connectionHash];
} else {
return self::createConnection($host, $username, $password, $db);
}
return false;
}
}
$connection = dbConnectionPooler::getConnection("dbhost", "dbuser", "dbpassword", "mydb");
?>