【问题标题】:MySQL PDO - What should be inside the try { block }?MySQL PDO - try {块}里面应该是什么?
【发布时间】:2012-06-17 21:03:10
【问题描述】:

所以我正在学习 PDO,并从标准的 PHP MySQL 函数进行转换。但是,我有一个问题。关于try {} 块,它们到底应该在里面,什么应该在外面?

所有使用$sth-> ... 的东西都应该在try {} 里面吗?它应该只是从语句第一次准备到执行的时候吗?比这还少?

任何帮助将不胜感激。 :)

这是我在课堂上的一个示例方法。组织得当吗?请注意我是如何将 everything 放入 try {} 的。那是错的吗?对我来说感觉不正确,但我不知道我应该如何改变它。

protected function authorized()
{
    try
    {
        // Attempt to grab the user from the database.
        $sth = $dbh->prepare("
            SELECT COUNT(*) AS num_rows
            FROM users
            WHERE user_id = :user_id
            ");

        $sth->bindParam(':user_id', $this->user_id);
        $sth->execute();

        // Check if user exists in database.
        if ($sth->fetch()->num_rows > 0)
        {
            // User exists in database, and is therefore valid.
            return TRUE;
        }
        else
        {
            // User does not exist in database, and is therefore invalid.
            return FALSE;
        }
    }
    catch (PDOException $e)
    {
        pdo_error($e);
    }
}

【问题讨论】:

  • 前几天我也在工作中问同样的问题!一切顺利吗?
  • 非常好的问题。很多开发人员都不知道这个主题

标签: php mysql pdo


【解决方案1】:

try catch 应该在函数之外

<?php

protected function authorized() {
    // Attempt to grab the user from the database.
    $sth = $dbh->prepare("
            SELECT COUNT(*) AS num_rows
            FROM users
            WHERE user_id = :user_id
            ");

    $sth->bindParam(':user_id', $this->user_id);
    $sth->execute();

    // Check if user exists in database.
    if ($sth->fetch()->num_rows > 0) {
        // User exists in database, and is therefore valid.
        return TRUE;
    }
    else {
        // User does not exist in database, and is therefore invalid.
        return FALSE;
    }
}

...

try {
    authorized()
}
catch (PDOException $e) {
    pdo_error($e);
}

不要在方法内部处理异常。您尝试 方法捕获如果发生异常。

【讨论】:

  • 嗯,好吧,在这种情况下是有道理的。如果它不在函数内部怎么办?在我的另一个脚本中,我有几个嵌套循环和条件,等等,它有几百行长。在那种情况下,我会将整个代码块包装在try {} 中吗?换句话说,一切都应该在try {} 中吗?“一切”是指使用$dbh$sth 的任何东西?
  • 如果该方法抛出的不是PDOException 怎么办?
  • @Mike:你也捕获了一个Exception,它是泛型类型,将捕获所有异常类型。您可以捕获多个异常。
  • @NathanaelShermett:是的。但总的来说,你所有最有可能抛出异常的业务逻辑都应该在类和方法中。在您需要在函数之外执行代码并抛出异常的情况下,您应该将 try/catch 包装在所有内容上。
  • 这不是完全 与没有具有适当错误模式的 try catch 块相同吗? try catch 应该用于从脚本推断不同的行为,而不仅仅是报告无论如何都会报告的错误 - stackoverflow.com/questions/23571128/…
猜你喜欢
  • 2021-01-17
  • 2016-03-28
  • 1970-01-01
  • 2012-10-02
  • 1970-01-01
  • 2021-05-02
  • 2021-01-27
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多