0

Is it acceptable practice to use PHP's ternary operator to check for successful INSERT in database (or more generally, the return value of any function)? The PHP manual seems to be cautious on stacked ternary operators, and I have some embedded in my writeData function.

#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.");

Edit:

I actually try & catch in the writeData function. I'm not yet outputting error pages. Assuming I write error page code and output it next in the catch block of writeData, is it best to do:

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

(or alternatively the ternary version, which I kinda agree is hard to read especially in this case)

Escher
  • 5,418
  • 12
  • 54
  • 101

2 Answers2

1

In this specific case, no, it's not acceptable. or die is the 2000's way to deal with errors, as of 2015 you're supposed to use exceptions (that's what they are for):

try {
    writeData($conn, $form);
} catch(PDOException $e) {
   // try to recover, if possible
   // log the error
   // give the user a nicely formatted error page
}
georg
  • 211,518
  • 52
  • 313
  • 390
  • I actually `try` & `catch` in `writeData`. Is this the best place to do this (i.e. handle exceptions in the function that executes the query)? I've updated the question with better information. – Escher Feb 27 '15 at 09:56
  • @Escher: that's another question, and has nothing to do with ternary operator. A general rule is that you shouldn't `catch` exceptions you can't handle. Since `writeData` can't do anything meaningful when an exception occurs, you should allow the exception to bubble up to the front controller, which then has to decide what to do: recover from the error, or try something else, or inform the user and exit. – georg Feb 27 '15 at 10:00
0

In my opinion it is never good practice to use the ternary operator. Proper conditionals are always easier to read and understand. The debate goes on.

Community
  • 1
  • 1
phpPhil
  • 906
  • 1
  • 9
  • 28