Skip to content

Instantly share code, notes, and snippets.

@ranaroussi
Created October 10, 2013 08:51
Show Gist options
  • Save ranaroussi/6915199 to your computer and use it in GitHub Desktop.
Save ranaroussi/6915199 to your computer and use it in GitHub Desktop.
Connect to multiple mysql servers. $db = new multi_mysqli(array('host1', 'host2'), 'root', '123456', 'test');
<?php
/**
* Multi-Server MySQLi class
* Givan a list of MySQL hosts, the client will connect to the first available server
* $servers can be an string for single server, or, for multiple server, use an array or comma-separated list
*/
class multi_mysqli extends mysqli {
// example from: http://php.net/manual/en/mysqli.real-connect.php
public function __construct($servers=array(), $username='', $password='', $database='test') {
try {
if (!is_array($servers)) {
if ($servers) {
// build array if empty
$servers = explode(',', trim(str_replace(' ', '', $servers), ','));
}
if (empty($servers)) {
throw new Exception('No MySQL servers provided.');
}
}
// init mysqli
@parent::init();
// set connect timeout to 1 sec
@parent::options(MYSQLI_OPT_CONNECT_TIMEOUT, 1);
do {
$server = array_shift($servers);
$connected = @parent::real_connect(trim($server), trim($username), trim($password), trim($database));
// next time wait 10 seconds for a connection
if (!$connected) parent::options(MYSQLI_OPT_CONNECT_TIMEOUT, 10);
} while (!$connected);
} catch (Exception $e) {
die($e->getMessage());
}
}
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment