Search code examples
phpmysqldatabasewampserverfailover

how to conect to secondary database if primary database is down (PHP)


i hope someone can help me, ive been struggling on this for 3 days now.

here is my situation, i am making a website with php, and i have 2 computers as servers with wampserver...

main server is 192.168.0.10

secondary server is 192.168.0.12

and a virtual machine where im trying out if the remote conection works

my website is hosted on my main server so the conexion query is...

$conexion = mysqli_connect("localhost","root","","dbdaq");

it works fine, i even have master to master replication on the servers.

but what i need to do is that when main server is down it needs to try to conect to the database on the seondary database, so im trying to use the code...

$conexion = mysqli_connect("localhost","root","","dbdaq");


if (!$conexion){
    $conexion = mysqli_connect("192.168.0.12","root","password","dbdaq");
}

but when i manually turn of the mysql services on main server it doesnt actually try to use the other servers database...

it keeps giving me the error that says

Warning: mysqli_connect(): (HY000/2002): No connection could be made because the target machine actively refused it. in C:\wamp64\www\PaginaV2\Pagina\PHP y JS\Procesoalumno.php on line 2


Solution

  • Try this: use php's @ operator (the error control operator) to suppress the error message from the first connection failure. Try this.

    $conexion = @mysqli_connect("localhost","root","","dbdaq");
    
    if ( !$conexion ) {
        $conexion = mysqli_connect("192.168.0.12","root","password","dbdaq");
    }
    

    It seems likely your code for the failover connection works correctly, but you still get an obnoxious error message. The @ operator suppresses the message.