如何处理PDO异常 [英] How to handle PDO exceptions
本文介绍了如何处理PDO异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
PDO
类,但是我有一些麻烦找到正确的方法来处理错误,我写了这段代码: <?php
// $连接alreay创建在类似UPDATE语句的类上
/ /我只是简单地添加了trim()和PDO :: PARAM ...数据类型
$ id = 33;
$ name =Mario Bros.;
$ url =http://nintendo.com;
$ country =jp;
try {
$ sql =UPDATE table_users SET name =:name,url =:url,country =:country WHERE user_id =:user_id
$ statement = $ connection-> prepare($ sql);
$ statement-> bindParam(':user_id',trim($ id),PDO :: PARAM_INT);
$ statement-> bindParam(':name',trim($ name),PDO :: PARAM_STR);
$ statement-> bindParam(':url',trim($ url),PDO :: PARAM_STR);
$ statement-> bindParam(':country',trim($ country),PDO :: PARAM_STR,2);
$ status = $ statement-> execute();
} catch(PDOException $ e){
print $ e-> getMessage();
}
print $ status; //它返回一个空值,并且没有报告错误
?>
这部分代码不报告错误,但它根本不起作用,var $ status
在底部,返回一个空值。
有人可以帮我找到我错的地方吗?
解决方案
PDO不会抛出异常,除非你告诉它。你运行:
$ connection-> setAttribute(PDO :: ATTR_ERRMODE,PDO :: ERRMODE_EXCEPTION);
在PDO对象上?
I'm trying to work with PDO
class on php but I have some trouble to find the right way to handle errors, I've wrote this code:
<?php
// $connection alreay created on a class which works with similar UPDATE statements
// I've simply added here trim() and PDO::PARAM... data type
$id = 33;
$name = "Mario Bros.";
$url = "http://nintendo.com";
$country = "jp";
try {
$sql = "UPDATE table_users SET name = :name, url = :url, country = :country WHERE user_id = :user_id";
$statement = $connection->prepare ($sql);
$statement->bindParam (':user_id', trim($id), PDO::PARAM_INT);
$statement->bindParam (':name', trim($name), PDO::PARAM_STR);
$statement->bindParam (':url', trim($url), PDO::PARAM_STR);
$statement->bindParam (':country', trim($country), PDO::PARAM_STR, 2);
$status = $statement->execute ();
} catch (PDOException $e) {
print $e->getMessage ();
}
print $status; // it returns a null value, and no errors are reported
?>
this portion of code doesn't report errors, but it simply doesn't work, the var $status
at the bottom, return a null value.
can someone help me to find where I'm wrong?
解决方案
PDO won't throw exceptions unless you tell it to. Have you run:
$connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
on the PDO object?
这篇关于如何处理PDO异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文