0

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

trumanblack1025
  • 471
  • 2
  • 8
  • 19

3 Answers3

0

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;
}
Matt Clark
  • 27,671
  • 19
  • 68
  • 123
  • thank you so much! how can I stop stop it from displaying a warning message? – trumanblack1025 Feb 10 '17 at 21:42
  • I am assuming that you mean PHP itself is printing errors, other then those explicitly printed in the above code, correct? [That is going to be a setting in php.ini](http://stackoverflow.com/a/21429652/1790644), [or like this](http://stackoverflow.com/a/15949445/1790644). – Matt Clark Feb 10 '17 at 21:51
0

$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.

John Zenith
  • 472
  • 5
  • 10
0

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)