PDO request error, but I do not see any errors. How to get error message from PDO?
To be able to see database errors, you need to set PDO errmode to exceptions. Exceptions are better than ordinary errors in different ways: they always contain a stack trace, they can be caught using try..catch or processed using a special error handler. And even unprocessed, they act like regular PHP errors, providing all the important information by following the error reporting settings on the site.
Please note that setting this mode as the connection parameter will allow PDO to exclude exceptions from connection errors, which is very important.
So, here is an example to properly create a PDO connection:
$dsn = "mysql:host=$host;dbname=$db;charset=utf8"; $opt = array( PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, // other options ); $pdo = new PDO($dsn, $user, $pass, $opt);
Thus, you will always be notified of all database errors that occur during query execution. Note that you should be able to see PHP errors in general. On a real site, you need to look at the error logs, so the settings should be
error_reporting(E_ALL); ini_set('display_errors',0); ini_set('log_errors',1);
while on the local development server it is ok to make errors on the screen:
error_reporting(E_ALL); ini_set('display_errors',1);
and of course, you should never use the error suppression operator ( @ ) before your PDO statements.
In addition, due to many bad examples telling about wrapping each PDO statement in a try..catch block, I have to make a separate note:
DO NOT use the try..catch statement to echo the error message. An exception for exceptions is already great for this purpose, because it will act just like other PHP errors - so you can determine the behavior using the site settings - so you will get an error message without this useless code. While an unconditional error echo may reveal some sensitive information to a potential attacker, but confuse an honest visitor,
- a custom exception handler can be added later, but not required. Especially for new users it is recommended to use unhandled exceptions, as they are extremely informative, useful and safe.
- Use
try..catch only if you are going to handle the error itself - say, rollback a transaction.