PDO不会在错误的SQL查询上引发异常 [英] PDO not throwing exception on wrong SQL query

查看:48
本文介绍了PDO不会在错误的SQL查询上引发异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对MySQLi非常熟悉,并且正在尝试PDO,听说它更好.我正在阅读本教程这里.他们说,当设置了PDO :: ERRMODE_EXCEPTION时,PDO会引发异常,并且我们不小心对查询进行了某些错误(例如,错误地键入了它,使用DELECT而不是SELECT).我输入了相同的错误查询,以查看本地环境中的错误和异常消息.我在32位Windows 7 PC上安装了PHP 5.5,MySQL 5.6和Apache 2.4.9的最新WAMP,但没有达到我的期望,也没有抛出异常.我尝试了教程中发布的相同代码:

I am pretty much familiar with MySQLi and was trying PDO, I heard it is better. I was going through the tutorial present here. They say that PDO throws an exception when PDO::ERRMODE_EXCEPTION is set and we accidentally do something wrong with the query (for example, typing it incorrectly, DELECT instead of SELECT). I typed in the same wrong query to see the error and exception message on my local environment. I have latest WAMP installed with PHP 5.5, MySQL 5.6 and Apache 2.4.9 in my 32-bit Windows 7 PC, but did not get what I was expecting, no exception was thrown there. I tried the same code posted in the tutorial:

try {
$DBH = new PDO("mysql:host=$host;dbname=$dbname", $user, $pass);
$DBH->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );

# UH-OH! Typed DELECT instead of SELECT!
$DBH->prepare('DELECT name FROM people');
}
 catch(PDOException $e) {
 echo "I'm sorry, Dave. I'm afraid I can't do that.";
 file_put_contents('PDOErrors.txt', $e->getMessage(), FILE_APPEND);
}

没有PDOError.txt,没有错误消息.本教程或我的环境有问题吗?还是在某些情况下PDO无法引发异常?我已经为MySQL安装了PDO驱动程序.

No PDOError.txt, no error message. Is something wrong with the tutorial or my environment? Or there are cases where PDO fails to throw exceptions? I have PDO driver installed for MySQL.

推荐答案

由于查询从未执行且正在等待进一步的指令,因此可能会失败.

It's probably failing because the query never gets executed and is awaiting further instructions.

由于它认为什么都不会触发,所以在PDO看来这都是有效的.这就是我的比喻.

Since it figures that nothing fires, then it's all valid in the eye of PDO; that is my analogy on this.

执行它,您将看到它会引发异常.

Execute it and you will see it will throw an exception.

或者是在准备之后执行它,或者是一个简单的->query()而不是->prepare().

Either by executing it after the prepare, or a simple ->query() rather than ->prepare().

这篇关于PDO不会在错误的SQL查询上引发异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆