Is there any way to catch MySQL and database errors in PHP?

ASD picture ASD · May 25, 2011 · Viewed 29k times · Source

Sometimes I am getting a database error like

Warning: mysql_connect() [function.mysql-connect]: Access denied for user 'test'@'101.190.193.83' (using password: YES)

Could not connect: Access denied for user 'test'@'101.190.193.83' (using password: YES)"

But truly there is no change in the password.

Is there any way to capture this error in a log file and show some nice message on the screen, like "Server error. Please try again some time."

Answer

Gérald Croës picture Gérald Croës · May 25, 2011

If you don't want PHP to show the warning, you have to use the "@" operator

$connect = @mysql_connect(HOST, USER, PASS);//won't display the warning if any.
if (!$connect) { echo 'Server error. Please try again sometime. CON'; }

You may also consider setting display_errors to 0 in your php.ini file in production

You may also consider PDO for connecting to MySQL, it's using exceptions as a default to report errors,

try {
    $dbh = new PDO($dsn, $user, $password);
} catch (PDOException $e) {
    echo 'Could not connect : ' . $e->getMessage();
}