Home > Backend Development > PHP Tutorial > Optimizing Availability with MySQL Built-in Replication (6)_PHP Tutorial

Optimizing Availability with MySQL Built-in Replication (6)_PHP Tutorial

WBOY
Release: 2016-07-13 17:22:02
Original
760 people have browsed it

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.

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/532384.htmlTechArticleStep 5: An improved database connection program$#@60;?php /****** *************************************************** function db_connect_plus() returns a link identifier on succes...
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template