No. Unconditionally outputting connection errors on a web page gives hackers useful information -
- That they were able to caused a connection error, i.e. too many connections.
- A connection error contains the connection username, giving them half the information they need to break into your database.
- The error contains server path information, which can be used to find other ways of compromising your server.
Instead, use exceptions for database errors (connection, query, prepare, and execute) and in most cases let php catch the exception, where it will use its error related settings to control what happens with the actual error information (database errors will get displayed or logged the same as php errors.) The exception to this rule is when inserting/updating duplicate user submitted data. In this case, your code should catch the exception, detect if a duplicate key error occurred, and setup a user error message for the duplicate value.
If you are updating old code or writing new code, PDO is the simplest and most consistent way of doing so, since you must either convert or add protection against sql special characters in external/unknown data from breaking the sql query syntax (which is how sql injection is accomplished.) The following is typical PDO connection code -
$DB_HOST = 'localhost';
$DB_USER = '';
$DB_PASS = '';
$DB_NAME = '';
$DB_ENCODING = 'utf8'; // db character encoding
$pdo = new pdo("mysql:host=$DB_HOST;dbname=$DB_NAME;charset=$DB_ENCODING",$DB_USER,$DB_PASS);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // set the error mode to exceptions
$pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES,false); // run real prepared queries
$pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE,PDO::FETCH_ASSOC); // set default fetch mode to assoc
The PDO connection always uses exceptions. The above code sets the error mode to exceptions for all the other database statements.