如何处理PDO异常

vit*_*tto 17 php mysql pdo exception-handling

我正在尝试使用PDOPHP 上的类,但我找到正确的方法来处理错误,我写了这段代码:

<?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

?>
Run Code Online (Sandbox Code Playgroud)

这部分代码不报告错误,但它根本不起作用,$status底部的var 返回一个空值.

谁能帮我找到我错的地方?

Mat*_*chu 44

除非你告诉它,否则PDO不会抛出异常.你运行:

$connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
Run Code Online (Sandbox Code Playgroud)

在PDO对象上?

  • 找到它 - http://us3.php.net/manual/en/pdo.error-handling.php - "PDO :: ERRMODE_SILENT - 这是默认模式." (3认同)
  • @Matchu:是的你是对的,谢谢.仍然**`PDO :: __ construct()`如果尝试连接到请求的数据库失败**则抛出PDOException. (2认同)