php 如何处理 PDO 异常

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2104481/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 05:02:13  来源:igfitidea点击:

How to handle PDO exceptions

phpmysqlpdoexception-handling

提问by vitto

I'm trying to work with PDOclass on php but I have some trouble to find the right way to handle errors, I've wrote this code:

我正在尝试PDO在 php 上使用类,但在找到处理错误的正确方法时遇到了一些麻烦,我编写了以下代码:

<?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 $statusat the bottom, return a null value.

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

can someone help me to find where I'm wrong?

有人可以帮我找出我错在哪里吗?

回答by Matchu

PDO won't throw exceptions unless you tell it to. Have you run:

PDO 不会抛出异常,除非你告诉它。你有没有跑过:

$connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

on the PDO object?

在 PDO 对象上?

回答by TomerM

You can add the attribute one time while you connect you mysql.

您可以在连接 mysql 时添加该属性一次。

function connect($dsn, $user, $password){
    try {
        $dbh = new PDO($dsn, $user, $password, array(PDO::ATTR_ERRMODE => PDO::ERRMODE_WARNING));
    } catch (PDOException $e) {
        echo 'Connection failed: ' . $e->getMessage();
        exit;
    }
    }

Thanks

谢谢