I am not 100% sure in this, but pg_exec() could return 0 as Connection ID.
because of that i change some of my code like this:
$dbres = pg_exec($SQL);
if ($dbres === false){
echo "DB is down";
exit;
}else{
//do something
}