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

时间:2015-02-27 09:30:41

标签: php pdo ternary-operator

使用PHP的三元运算符来检查数据库中的成功INSERT(或更一般地说,任何函数的返回值)是否可以接受? 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。我还没有输出错误页面。假设我编写错误页面代码并将其输出到catch writeData块中的下一个,最好是这样做:

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

(或者三元版本,我有点同意很难阅读,特别是在这种情况下)

2 个答案:

答案 0 :(得分:1)

在这种特定情况下,不,它是不可接受的。 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
}

答案 1 :(得分:0)

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