Step 5: An improved database connection program
$#@60;?php
/********************************************************
function db_connect_plus()
returns a link identifier on success, or false on error
********************************************************/
function db_connect_plus(){
$username = "username";
$password = "password";
$primary = "10.1.1.1";
$backup = "10.1.1.2";
$timeout = 15; // timeout in seconds
if ($fp = fsockopen($primary, 3306, &$errno, &$errstr, $timeout)){
fclose($fp);
return $link = mysql_connect($primary, $username, $password );
}
if($fp = fsockopen($secondary, 3306, &$errno, &$errstr, $timeout)){
fclose($fp);
return $link = mysql_connect($secondary, $username, $password);
}
return 0;
}
?$#@62;
This new and improved function provides us with an adjustable The timeout feature is what the mysql_connect function lacks. If the connection fails immediately, which is the case if the machine is "alive" but mysqld is "down", the function is immediately moved to the second server. The above function is quite robust. Test it before attempting to connect to see if the service program is listening on the specified port. Let your script time out after an acceptable period of time, allowing you to handle error conditions appropriately. If you modify the default port 3306, please make sure to modify the port number.