Use mysql_pconnect , which will do what you want.
Firstly, when connecting, the function will first try to find a (permanent) link that is already open with the same host, username and password. If it is found, the identifier for it will be returned instead of opening a new connection.
You can also use a static or singleton class to manage the connection pool 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"); ?>
source share