简体   繁体   中英

Check if remote database is connected

I'm currently connecting to a remote database

mysqli_connect('ip','username','password','db');

the connection is successful but I want to have validations if the computer is offline. how can I validate it? Thanks

Did you read the documentation ?

Literally the only example on the page:

$link = mysqli_connect("127.0.0.1", "my_user", "my_password", "my_db");

if (!$link) {
    echo "Error: Unable to connect to MySQL." . PHP_EOL;
    echo "Debugging errno: " . mysqli_connect_errno() . PHP_EOL;
    echo "Debugging error: " . mysqli_connect_error() . PHP_EOL;
    exit;
}

$mysql = mysqli_connect('ip','username','password','db');

// stop execution if error occurs during the conbection
if ( mysqli_connect_errno ) exit( "failed");

// check if connection is active
if ( mysqli_ping( $mysql ) {
    echo 'alive';
} else {
    echo 'not active';

    mysqli_close( $mysql );
}

The `mysqli_ping()' function returns true on success, or false on failure.

You may open a socket to check if the DB server is up by the following function

 function ping($host, $port, $timeout) 
 { 
   $tB = microtime(true); 
   $fP = fSockOpen($host, $port, $errno, $errstr, $timeout); 
   if (!$fP) { return "down"; } 
   $tA = microtime(true); 
   return round((($tA - $tB) * 1000), 0)." ms"; 
 }

after that, you may use return argument of sqli_connect to check further test ( ie the MySql service is running,db exists or user is authenticated to use the db)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM