Skip to content

Instantly share code, notes, and snippets.

@ranaroussi
Last active January 9, 2020 19:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ranaroussi/64a26c9a2ec6d69c62ba7c650f49a8a0 to your computer and use it in GitHub Desktop.
Save ranaroussi/64a26c9a2ec6d69c62ba7c650f49a8a0 to your computer and use it in GitHub Desktop.
Multi-Server MySQLi class
<?php
/**
* Multi-Server MySQLi class
* https://gist.github.com/ranaroussi/64a26c9a2ec6d69c62ba7c650f49a8a0
*
* Copyright 2013-2020 Ran Aroussi
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
class MySQL_DB extends mysqli {
public function __construct($servers = array(), $username = '', $password = '', $database = 'test')
{
/**
* 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
*/
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