3

Every once in a while I get an error such as the following with PDO:

Error!: SQLSTATE[HY093]: Invalid parameter number: parameter was not defined

Is there any way to get a more specific error, such as a line number, filename, the parameter that is missing, etc., instead of a vague message?

Zuul
  • 16,217
  • 6
  • 61
  • 88
Nate
  • 26,164
  • 34
  • 130
  • 214
  • 2
    Set PDO to throw exceptions (`$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);`). This will cause your app to die and dump a stack trace when it happens - I do this as a matter of course and wrap every PDO operation/set of operations in a try/catch with error handling as appropriate. But frankly if your error log is not logging file/line no already and you need to do this, it's not up to much. – DaveRandom Sep 19 '12 at 22:14
  • @DaveRandom - I already have those settings set, and my queries are inside a try/catch block. I assume that's why I got the error I did. – Nate Sep 19 '12 at 22:16
  • Well in that case presumably you are doing something like `echo $e->getMessage()` in the `catch` block? Well change it to `echo $e->getMessage().' in '.$e->getFile().' on line '.$e->getLine();` instead and you'll get the information you want. See http://www.php.net/manual/en/class.exception.php – DaveRandom Sep 19 '12 at 22:20
  • @DaveRandom - Thanks, that is very helpful! Would you like to post that as an answer? – Nate Sep 19 '12 at 22:23

2 Answers2

5

Firstly, ensure that you have PDO set to throw exceptions on error:

$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

Now, ensure that every PDO operation/set of operations is enclosed a try/catch block, something like this:

try {

  $stmt = $pdo->prepare("SELECT * FROM Whatever");
  // ...yada yada yada, your PDO code goes here

} catch (PDOException $e) {

  // This will echo the error message along with the file/line no on which the
  // exception was thrown. You could e.g. log the string to a file instead.
  echo $e->getMessage().' in '.$e->getFile().' on line '.$e->getLine();

}

All exceptions extend from the base Exception class, and so inherit it's methods and the information it carries about errors.

As a side note, if using PDO with MySQL, ensure that you disable emulated prepared statements. See here for more info on how to do this and why you should.

Community
  • 1
  • 1
DaveRandom
  • 87,921
  • 11
  • 154
  • 174
1

What you can do is register a global error handler and a global exception handler. Those functions receive filename, linenumber and error message. In those functions, echo the data to the screen and die.

JvdBerg
  • 21,777
  • 8
  • 38
  • 55