note 125530 deleted from function.mysql-pconnect by cmb

From: Date: Sat, 21 Nov 2020 10:20:10 +0000
Subject: note 125530 deleted from function.mysql-pconnect by cmb
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-215877@lists.php.net to get a copy of this message
Note Submitter: mtba5i dot com at hotmail dot com ---- Here's a nifty little class which will load balance across multiple replicated MySQL server instances, using persistent connections, automatically removing failed MySQL servers from the pool. You would ONLY use this for queries, never inserts/updates/deletes, UNLESS you had a multi-master situation where updates to any database serverautomatically replicate to the other servers (I don't know whether that's possible with MySQL). Using this class, you get a connection to a MySQL server like this: $con = MySQLConnectionFactory::create(); Here is the class (you'll need to customize the $SERVERS array for your configuration -- note that you would probably use the same username, password and database for all of the servers, just changing the host name, but you're not forced to use the same ones): <?php class MySQLConnectionFactory { static $SERVERS = array( array( 'host' => 'myHost1', 'username' => 'myUsername1', 'password' => 'myPassword1', 'database' => 'myDatabase1'), array( 'host' => 'myHost2', 'username' => 'myUsername1', 'password' => 'myPassword2', 'database' => 'myDatabase2') ); public static function create() { // Figure out which connections are open, automatically opening any connections // which are failed or not yet opened but can be (re)established. $cons = array(); for ($i = 0, $n = count(MySQLConnectionFactory::$SERVERS); $i < $n; $i++) { $server = MySQLConnectionFactory::$SERVERS[$i]; $con = mysql_pconnect($server['host'], $server['username'], $server['password']); if (!($con === false)) { if (mysql_select_db($server['database'], $con) === false) { echo('Could not select database: ' . mysql_error()); continue; } $cons[] = $con; } } // If no servers are responding, throw an exception. if (count($cons) == 0) { throw new Exception ('Unable to connect to any database servers - last error: ' . mysql_error()); } // Pick a random connection from the list of live connections. $serverIdx = rand(0, count($cons)-1); $con = $cons[$serverIdx]; // Return the connection. return $con; } } ?> Source: https://www.el7lwa.com

« previous php.notes (#215877) next »