How to get more information from PDO failure “Error!: SQLSTATE[HY093]: Invalid parameter number: parameter was not defined”?

风流意气都作罢 提交于 2019-12-23 18:03:54

问题


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?


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/12503462/how-to-get-more-information-from-pdo-failure-error-sqlstatehy093-invalid-p

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!