Tuesday, 15 May 2012

php - Suppressing PDO Warnings -



php - Suppressing PDO Warnings -

i'm trying display server status, based upon whether database can connected or not. old school mysql_connect() , mysqli_connect() easy. i'm trying remain modern, i'm using pdo, can't figure out how-to suppress default warning. can tell, need utilize getmessage() function print pdo warning, i'm not using it.

here's code:

8 $dbstatus = 1; 9 seek { 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 supplied , correct, except $dbhost, intentionally broken test this. now, produces desired results, prints warning message too:

warning: pdo::__construct(): php_network_getaddresses: getaddrinfo failed: no such host known. in c:\xampp\htdocs\cd\includes\dbconnect.php on line 10

if right $dbhost variable, works fine, know issue isn't pdo statement beingness usable.

any ideas on i'm missing?

solution

i used variation of supplied jeroen:

if(filter_var(gethostbyname($dbhost), filter_validate_ip)) { $dbstatus = 1; seek { $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 help , hope helps else! ^^

the thing can see here, tell pdo throw exceptions after have tried open connection. late.

what instead, send alternative constructor straight using 4th parameter:

try { $opts = array(pdo::attr_errmode => pdo::errmode_exception); $db = new pdo($dbms . ':host=' . $dbhost . ';port=' . $dbport . ';dbname=' . $dbname, $dbuser, $dbpasswd, $opts); } catch(pdoexception $e) { ...

that solve problem.

edit: if host name provided user, validate before sending pdo constructor.

for illustration using:

if (filter_var(gethostbyname($user_provided_host_name), filter_validate_ip)) { // valid hostname / ip address }

that work domain names, localhost , ip addresses.

php mysql pdo exception-handling suppress-warnings

No comments:

Post a Comment