I am trying to display server status based on whether a database can be connected or not. With the old school, mysql_connect() and mysqli_connect() was easy. I try to stay up-to-date, so I use PDO, but I cannot figure out how to suppress the default warning. From what I can say, you need to use the getMessage() function so that it prints a PDO warning, but I do not use it.
Here is my code:
8 $dbstatus = 1; 9 try { 10 $db = new PDO($dbms . ':host=' . $dbhost . ';port=' . $dbport . ';dbname=' . $dbname, $dbuser, $dbpasswd); 11 $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); 12 } catch(PDOException $e) { 13 $dbstatus = 0; 14 } 15 if($dbstatus == 1) { 16 echo '<span style="color: green">DB Up</span>'; 17 } else { 18 echo '<span style="color: red">DB Down</span>'; 19 exit; 20 }
All connection variables are supplied and corrected, with the exception of $dbhost , which is intentionally broken to verify this. Now it gives the desired results, but also displays a warning message:
Warning : PDO :: __ construct (): php_network_getaddresses: getaddrinfo failed: this host is not known. in C: \ xampp \ htdocs \ cd \ includes \ dbconnect.php on line 10
If I fix the $dbhost variable, it works fine, so I know that the problem is not that the PDO instruction can be used.
Any ideas on what I am missing?
Decision
I used a variation of what was given by jeroen:
if(filter_var(gethostbyname($dbhost), FILTER_VALIDATE_IP)) { $dbstatus = 1; try { $db = new PDO($dbms . ':host=' . $dbhost . ';port=' . $dbport . ';dbname=' . $dbname, $dbuser, $dbpasswd, array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION)); } catch(PDOException $e) { $dbstatus = 0; } } else { $dbstatus = 0; } if($dbstatus == 1) { echo '<span style="color: green">DB Up</span>'; } else { echo '<span style="color: red">DB Down</span>'; exit; }
Thanks for the help and I hope this helps someone else! ^^