I'm trying to display a server status, based upon whether the database can be connected to or not. With the old school mysql_connect()
and mysqli_connect()
it was easy. I'm trying to stay modern, so I'm using PDO, but I can't figure out how-to suppress the default warning. From what I can tell, you need to use the getMessage()
function for it to print the PDO warning, but I'm not using it.
Here's 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 the connection variables are supplied and correct, except the $dbhost
, which is intentionally broken to test this. Now, it produces the desired results, but is also prints a warning message too:
Warning: PDO::__construct(): php_network_getaddresses: getaddrinfo failed: No such host is known. in C:xampphtdocscdincludesdbconnect.php on line 10
If I correct the $dbhost
variable, it works fine, so I know the issue isn't with the PDO statement being usable.
Any ideas on what I'm missing?
Solution
I used a variation of what was supplied 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;
}
Thank you for the help and I hope this helps someone else! ^^
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…