如何处理 PDO 异常 [英] How to handle PDO exceptions
本文介绍了如何处理 PDO 异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试在 php 上使用 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
?>
这部分代码不报告错误,但它根本不起作用,底部的 var $status
返回空值.
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 不会抛出异常,除非你告诉它.你跑了吗:
PDO won't throw exceptions unless you tell it to. Have you run:
$connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
在 PDO 对象上?
这篇关于如何处理 PDO 异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文