我使用的是典型的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子句不拿出一个行更新,这将是在商业意识非常适合将捕捉到的异常。
是否有这样的方式,如果不进行更新,以抛出一个错误?
抛出自己的异常,如果更新未成功完成(或一组$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;