No. Don’t let a visitor to your site know what kind of internal error occurred, ever. This will only confuse a legitimate visitor with information they cannot do anything about and will let hackers know that they were successful in creating a connection error, encouraging them to do more of the same. All the visitor to your site needs to know is that a web page isn’t working, which if you do the following will cause a generic http 500 error page, which you can create your own if you choose.
When you, the developer/programmer are learning, developing, and debugging code/query(ies), you want to display all php and all failed statement errors. When on a live/public server, you want to log this information. To do this for database statement errors, SIMPLY let php catch and handle the exception, where php will use its error related settings to control what happens with the actual error information. You would then remove any existing database statement error handling logic, simplifying the code, since it will no longer get executed upon an error (execution transfers to the nearest correct type of exception handling, which will be php in this case.) Also, a connection error is a fatal problem for a database dependent web page and the posted code, since it doesn’t stop execution upon a connection error, will cause meaningless follow-on database statement errors when the code tries to use the nonexistent connection.
The only time having try/catch logic in your code for a database statement error is useful are for visitor recoverable errors, such as when inserting/updating duplicate or out of range data.
As to the posted connection code, also -
- Set the character set to match your database table(s).
- Set emulated prepared queries to false (you want to run real prepared queries.)
- Set the default fetch mode to assoc (so that you don’t need to keep specifying it in each fetch statement.)