1

I recently missed the PDO syntax and it took me a few hours to figure out what the error was. No error has been reported on the page. It was not for codamental catch.

How can I show error in these cases?

I used

new PDO ("mysql:localhost; dbname=crud", "root", "");

When the correct one was

new PDO ("mysql:host=localhost; dbname=crud", "root", "");

Yes I have

ini_set ('error_reporting', E_ALL);
ini_set ('display_errors', 1);

activated and the condition

try {} catch (PDOException $ e) {}

and even then no error is displayed.

Bruno Andrade
  • 565
  • 1
  • 3
  • 17
  • Ensure you have set `ini_set('error_reporting', E_ALL);` and `ini_set('display_errors', 'on');` otherwise a blank page will be displayed.The [PDO](https://secure.php.net/manual/en/pdo.construct.php) constructor should throw an exception upon failure to connect to the specified database. In which case you would need to use a [`try/catch`](https://secure.php.net/manual/en/language.exceptions.php#language.exceptions.catch) block to handle the error as desired – Will B. Jan 05 '19 at 10:54
  • 1
    Possible duplicate of [How do I get PHP errors to display?](https://stackoverflow.com/questions/1053424/how-do-i-get-php-errors-to-display) – Will B. Jan 05 '19 at 10:55
  • 1
    It is not duplicate. Even with these settings no error is displayed – Bruno Andrade Jan 05 '19 at 11:18
  • You have to ensure `ini_set('error_reporting', E_ALL); ini_set('display_errors', 1);` are both above the `new \PDO()` line for them to be applied if they are disabled in your ini file. As per https://3v4l.org/napvC You should actually see a `SQLSTATE[HY000] [2002]` exception immediately since `new PDO` has to be called before using `$pdo->setAttribute()`. Otherwise with either disabled, you will see no errors https://3v4l.org/AIUns and https://3v4l.org/QRELl – Will B. Jan 08 '19 at 18:26

1 Answers1

2

PDO has default mode silent (PDO::ERRMODE_SILENT). That means it won't throw exception on bad connection. So you need to set its attribute mode to throw exception:

try {

    $dbh = new PDO ("mysql:localhost; dbname=crud", "root", "");
    $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

} catch (PDOException $e) {

    echo 'Bad Connection. Error: ' . $e->getMessage();

}

more details here: http://php.net/manual/en/pdo.error-handling.php

Nikola Kirincic
  • 3,651
  • 1
  • 24
  • 28
  • `PDO::__construct` does throw an exception by default https://3v4l.org/napvC, as such `::setAttribute` is never called. The `::setAttribute(PDO::ATTR_ERRMODE)` applies for all other method calls from the PDO instanced object, such as `->prepare()`. – Will B. Jan 08 '19 at 18:35