vendredi 23 octobre 2020

INSERT or UPDATE: Try / Catch VS If / Else

I need some advice; I'm rewriting an application for my college that handles a lot of insert-or-update logic, but I'm working with external database tables (Banner) and PLSQL, so ORMs are pretty much out of the question.

A ton of the application is written using

try {
   // insert SARPHON here
}
catch(Exception $e) {
   // SARPHON record exists, update instead
}

Should I rewrite it using if / else code?

$count = oci_execute("select count(*) from SARPHON where ...");
if(empty($count))
    // .. do insert
else
    // .. do update

I was taught to never use try / catch as code flow structures (which is totally what the above is doing), but if I switch to the if / else code, it will always issue at least two sql statements. The try / catch method will issue one statement, and then only if it fails, a second one.

I know I could write it either way, but what is the "right" way to handle this?

Aucun commentaire:

Enregistrer un commentaire