PHP checks if remote MySQL server is available

I have several sites that use MySQL. I am not an expert in SQL, so I use simple join, queries, etc. Sometimes (rarely, but it happens) only the database server freezes, or I forgot to enable my mysql home testing. Until it works again, the server freezes, trying to connect, and finally a timeout error will occur.

I am trying to add a previous test of a database server, like this "ping" function:

function pingDomain($domain){ $starttime = microtime(true); $file = fsockopen ($domain, 80, $errno, $errstr, 10); $stoptime = microtime(true); $status = 0; if (!$file) { $status = -1; // Site is down } else { fclose($file); $status = ($stoptime - $starttime) * 1000; $status = floor($status); } return $status; } 

But it didn’t work, php freezes. Any ideas?

+4
source share
2 answers

Cannot find documentation for reliable and easy testing of mySQL server. Now I am using the following technique:

 @$this->Base = mysqli_init(); @$this->Base->options(MYSQLI_OPT_CONNECT_TIMEOUT, 1); @$this->Base->real_connect($host, $usuario, $senha, $bd); 

What will you catch the error with $ this-> Base-> connect_error or $ this-> Base-> connect_errno, it will not be written due to the "@" characters.

You can also use the procedural form:

 $Link = mysqli_init(); mysqli_options($Link, MYSQLI_OPT_CONNECT_TIMEOUT, 1); $res = @mysqli_real_connect($host, $usuario, $senha, $bd); if($res) { $E->echop("Connected!!!"); } else { $E->echop("Huston, we got a problem..."); } 

Comments and other answers are welcome!

0
source

Simple use of mysql_ping:

  <?php set_time_limit(0); $conn = mysql_connect('localhost', 'mysqluser', 'mypass'); $db = mysql_select_db('mydb'); /* Assuming this query will take a long time */ $result = mysql_query($sql); if (!$result) { echo 'Query #1 failed, exiting.'; exit; } /* Make sure the connection is still alive, if not, try to reconnect */ if (!mysql_ping($conn)) { echo 'Lost connection, exiting after query #1'; exit; } mysql_free_result($result); /* So the connection is still alive, let run another query */ $result2 = mysql_query($sql2); ?> 

You can take a look at this:

mysql_ping

+1
source

Source: https://habr.com/ru/post/1436444/


All Articles