Skip to content
Advertisement

Updating postgres with if conditions on parameters

I am trying to do a postgres update using if conditions to check if a parameter is empty before attempting to update.

The desired result would be not to update when the parameter is an ampty string.

I cannot seem to figure out the correct way to do this. My first attempt is below:

JavaScript

and then my second attempt was using:

JavaScript

What is the correct way of doing this with IF statements?

Advertisement

Answer

  • Probably the best way would be not to execute the statement; the PHP code already knows that the parameter is empty, so it can refrain from calling the $stmt->execute() (and surrounding code). That will also save the round-trip time to the database.
    JavaScript
  • If you do need to have the condition in the PostgreSQL query, note that IF is a statement, not an expression. The equivalent for expressions is CASE, something like:
    JavaScript
  • In this particular case, you can also put the condition as part of the WHERE clause:
    JavaScript
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement