PDO 故障排除:执行准备好的语句时未捕获错误
我在使用 PDO 时遇到了问题,因为未捕获错误。
代码很简单并且工作得很好,我只包含一个示例以避免混淆:
$sql = 'INSERT INTO somedatetable (something)
VALUES (:something)
ON DUPLICATE KEY UPDATE something=:something';
$values = array(":something" => $something);
try {
$stmt = $dbh->prepare($sql);
$stmt->execute($values);
} catch (PDOException $e) {
echo "Error: " . $e->getMessage() . "<br />\n";
}
代码工作正常,但是在处理新模块时,我遇到了一个问题,没有添加或修改记录,也没有捕获错误。
$stmt
返回了 false
但我不知道为什么或如何找到错误。
最后的解决方案很简单,我使用的是一个有限的 MySQL 用户,该用户没有对表的写权限。 使用 mysql 时,这些错误总是立即显示,但使用 PDO 时,我不知道如何获取它们。
如何让 PHP / PDO 显示或捕获此类数据库错误?
I have run into a problem using PDO because an error was not caught.
The code is simple and works just fine, I'll just include a sample to avoid confusion:
$sql = 'INSERT INTO somedatetable (something)
VALUES (:something)
ON DUPLICATE KEY UPDATE something=:something';
$values = array(":something" => $something);
try {
$stmt = $dbh->prepare($sql);
$stmt->execute($values);
} catch (PDOException $e) {
echo "Error: " . $e->getMessage() . "<br />\n";
}
The code works fine, however when working on a new module, I ran into a problem that no records were added or modified and no error was caught.
$stmt
returned false
but I did not have a clue why or how to find the error.
The solution was simple in the end, I was using a limited MySQL user that did not have write permissions to the table. These errors always displayed right away when using mysql, but using PDO I do not know how to get to them.
How do I get PHP / PDO to display or catch these kind of database errors?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
PDO::errorInfo()
或PDOStatement->errorInfo()
至于例外情况,请检查文档中的 PDO 中的“错误和错误处理”。 默认情况下不会引发异常,这就是您可能想要启用它们的原因。
另请参阅:
PDO::errorInfo()
orPDOStatement->errorInfo()
As for exceptions, check the docs for "Errors and error handling" in PDO. Exceptions aren't thrown by default, which is why you might want to enable them.
See as well: