Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to catch pg_connect() function error?

Tags:

php

postgresql

pg_connect() is showing the error in table format.Instead of showing error message as table format need a error message alert.

Error Message
Warning: pg_connect() [function.pg-connect]: Unable to connect to PostgreSQL server: FATAL: password authentication failed for user "test" in /home/test/public_html/QueueManager/Modules/Database.php on line 41

After if showing error as table format.
After executing pg_connect() throwed exception.
But is is not working.

Code

function connect()
{
  $HOST = $GLOBALS[Database_Conn][Db_Host];     # Host name 
  $USER = $GLOBALS[Database_Conn][Db_User];     # database user name 
  $DBNAME = $GLOBALS[Database_Conn][Db_Name];   # name of the database
  $PASSWORD = $GLOBALS[Database_Conn][Db_Pass]; # password the database user.

  try 
  {
    $conn = pg_connect("host=$HOST dbname=$DBNAME user=$USER ".
                       "password=$PASSWORD sslmode=disable");
    if(!$conn)
    {
      throw new Exception("Database Connection Error");
    }
    return $conn;
  }
  catch (Exception $e) 
  {
    print <<<_HTML_
    <script> alert('Caught exception'); 
    </script> _HTML_;
    die();
  }
}

Please give me the solution

like image 695
ungalnanban Avatar asked Nov 23 '10 05:11

ungalnanban


2 Answers

pg_connect does not throw exception, so you have to translate to exception like below.

function exception_error_handler($errno, $errstr, $errfile, $errline ) {
    throw new ErrorException($errstr, $errno, 0, $errfile, $errline);
}
set_error_handler("exception_error_handler");

try {
    $conn=@pg_connect("host=dbhost user=dbuser dbname=db password=dbpass");
} Catch (Exception $e) {
    Echo $e->getMessage();
}

Please refer this more detail

http://php.net/manual/en/language.exceptions.php

like image 161
user2548654 Avatar answered Sep 27 '22 21:09

user2548654


To hide the error text generated by PHP, add @ in front of the function call, e.g.:

$conn = @pg_connect("host=$HOST dbname=$DBNAME user=$USER ".
                   "password=$PASSWORD sslmode=disable");

More details here

like image 33
intgr Avatar answered Sep 27 '22 22:09

intgr