简体   繁体   English

PDO PHP未捕获的异常

[英]PDO PHP Uncaught exception

I have currently switched to using PDO but am having trouble in handling the exceptions. 我目前已切换为使用PDO,但在处理异常时遇到了麻烦。 The connection is correct and queries work perfectly, but when I put in a deliberate mistake the error is not handled as I would expect. 连接是正确的,查询可以正常工作,但是当我故意输入错误时,该错误未得到我所期望的处理。

I have changed the name of the table in my query to a table that does not exist. 我已将查询中的表名称更改为不存在的表。 From the code seen below, I would expect the page to print out 'Database Error' but instead get the horrible orange error saying... 从下面看到的代码中,我希望页面打印出“数据库错误”,但会显示可怕的橙色错误,提示...

'Uncaught exception 'PDOException' with message 'SQLSTATE[42S02]: Base table or view not found: 1146 Table 'test.post' doesn't exist' in C:\\wamp\\www\\website\\functions.php on line 46' '未捕获的异常'PDOException',消息为'SQLSTATE [42S02]:找不到基表或视图:1146第46行的C:\\ wamp \\ www \\ website \\ functions.php中的表'test.post'不存在'”

Here is the code when connecting the database... 这是连接数据库时的代码...

$hostname = 'localhost';
$username = '';
$password = '';
try{
    $dbh = new PDO("mysql:host=$hostname;dbname=test", $username, $password);
    $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
     print ("Database Error");
}

Am I making a mistake or is there a different way to handle PDO errors? 我是在犯错误还是有其他方法来处理PDO错误?

After connecting, you need to set the error handling: 连接后,需要设置错误处理:

$dbh = new PDO("mysql:host=$hostname;dbname=test", $username, $password);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

Edit: Note that the exception gets caught at the place it is thrown, so you need to put a try catch block around the query, the one you use when connecting only catches exceptions there (if any, see @Crontab's comment). 编辑:请注意,异常在抛出的地方被捕获,因此您需要在查询周围放置一个try catch块,连接时使用的那一类仅在那里捕获异常(如果有的话,请参见@Crontab的注释)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM