Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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."

like image 499
ASD Avatar asked May 25 '11 06:05

ASD


2 Answers

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();
}
like image 51
Gérald Croës Avatar answered Oct 02 '22 15:10

Gérald Croës


<?php
    $connect = mysql_connect(HOST, USER, PASS);
    if(!$connect) { echo 'Server error. Please try again sometime. CON'; }

    $select_db = mysql_select_db(DATABASE);
    if(!$select_db) { echo 'Server error. Please try again sometime. DB'; }
?>
like image 20
ChrisH Avatar answered Oct 02 '22 15:10

ChrisH