我使用的是典型的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子句没有要更新的行,所以从业务角度来说,捕获异常是理想的选择。
如果不进行更新,是否有办法抛出错误?
答案 0 :(得分:2)
如果更新未成功完成,将引发异常(或者,如果您不想引发异常,则设置$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;