使用三元运算符检查数据库中的 INSERT 是否成功?

Use ternary operator to check for successful INSERT in database?

使用 PHP 的三元运算符检查数据库中的 INSERT 是否成功(或更一般地说,任何函数的 return 值)是否可以接受? PHP 手册似乎对堆叠三元运算符持谨慎态度,我在 writeData 函数中嵌入了一些。

#pseudocode variables to give context
$conn = new PDO("mysql:host=localhost;dbname=blah", $user, $pass);
$form = sanitize($_POST);

#writeData returns true on success, false if PDO exception
#do nothing on success, warn if otherwise
writeData($conn, $form) ? : exit("Problem writing data to database.");

编辑:

我其实是try&catch中的writeData函数。我还没有输出错误页面。假设我编写错误页面代码并在 writeDatacatch 块中接下来输出它,最好是:

if(!writeData($conn, $form)) die();

(或者我同意三元版本很难阅读,尤其是在这种情况下)

在这种特定情况下,不,这是不可接受的。 or die 是 2000 年处理错误的方式,从 2015 年开始你应该使用异常(这就是它们的用途):

try {
    writeData($conn, $form);
} catch(PDOException $e) {
   // try to recover, if possible
   // log the error
   // give the user a nicely formatted error page
}

在我看来,使用三元运算符从来都不是好的做法。适当的条件总是更容易阅读和理解。 The debate goes on.