【问题标题】:PDO try/catch for the WHERE clause doesn't catch an errorWHERE 子句的 PDO 尝试/捕获未捕获错误
【发布时间】:2019-06-29 13:44:23
【问题描述】:

我使用的是典型的 PDO try/catch 子句,它可以正常工作,除了一个方面:WHERE 子句。

这是我的代码:

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

try {
    $cancel_query = "UPDATE table SET active = 0 WHERE id = $request_id";
    $cancel_stmt = $pdo->prepare($cancel_query);
    $cancel_stmt->execute();

    $message = "That request was successfully canceled.";

} catch (PDOException $e) {
    $message = 'This request was not canceled. Something went wrong. ' . $e->getMessage();
}

$pdo = null;

echo $message;

这将在大多数情况下捕获错误,例如如果我故意输入错误的表名或列名。但是,如果我输入一个不存在的 $request_id,则该消息将指示成功。由于没有更新任何内容,因为 WHERE 子句没有提供要更新的行,所以从业务角度来看,捕获异常是理想的。

如果没有更新,有没有办法抛出错误?

【问题讨论】:

标签: php pdo try-catch


【解决方案1】:

如果更新未成功完成,则抛出异常(或者如果您不想引发异常,请以不同方式设置 $message

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

try {
    $cancel_query = "UPDATE table SET active = 0 WHERE id = $request_id";
    $cancel_stmt = $pdo->prepare($cancel_query);
    $cancel_stmt->execute();

    if ($cancel_stmt->rowCount() < 1) //Count the number of affected rows, if less than 1 then none
    {
        throw new Exception('Oh no :('); // of course, write a proper error message
        // $message = "something is wrong"; // if you don't want to throw, set $message and use an else statement for the success message
    }
    else
    {
        $message = "That request was successfully canceled.";
    }

} catch (PDOException $e) {
    $message = 'This request was not canceled. Something went wrong. ' . $e->getMessage();
}
catch (Exception $ex)
{
   $message = 'This request was canceled. Something went wrong. ' . $ex->getMessage();
}

$pdo = null;

echo $message;

【讨论】:

  • 可以肯定地说,如果我要求 WHERE x = $x,而 $x 值不存在,这不构成错误吗?
  • 是的,我做到了。我没有收到任何错误。我只是想弄清楚其中的逻辑。我想如果你想更新,它会寻找要更新的东西,但没有找到,那么它就成功地完成了它的工作,只是没有任何变化。对吗?
  • 是的,对 :)。如果WHERE 子句为假,则不会发生任何事情,但这不是错误,只是正常行为
猜你喜欢
  • 2013-11-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-12-16
相关资源
最近更新 更多