如何从PDO失败“错误!:SQLSTATE [HY093]:无效的参数号:未定义参数"中获取更多信息? [英] How to get more information from PDO failure "Error!: SQLSTATE[HY093]: Invalid parameter number: parameter was not defined"?
问题描述
每隔一段时间,我都会收到诸如PDO的错误,如下所示:
Every once in a while I get an error such as the following with PDO:
错误!:SQLSTATE [HY093]:无效的参数编号:未定义参数
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?
推荐答案
首先,请确保您已将PDO设置为在发生错误时引发异常:
Firstly, ensure that you have PDO set to throw exceptions on error:
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
现在,确保每个PDO操作/一组操作都包含在try
/catch
块中,如下所示:
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();
}
所有异常都从 Exception
类扩展,因此继承了它的方法及其带来的有关错误的信息.
All exceptions extend from the base Exception
class, and so inherit it's methods and the information it carries about errors.
请注意,如果将PDO与MySQL一起使用,请确保禁用模拟的准备好的语句. 请参阅此处,以获取有关如何执行此操作以及为什么执行此操作的更多信息.
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.
这篇关于如何从PDO失败“错误!:SQLSTATE [HY093]:无效的参数号:未定义参数"中获取更多信息?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!