Apr
13
Conditional statements inside MySQL queries
Filed Under MySQL, Programming | 4 Comments
Often, when updating different values inside a MySQL table, extra selects, for example, might be needed. But that’s not always the case, because conditional statements can be used inside ordinary queries.
Let’s take a real world example: the table which holds informations about the timing in a test. So, the user is presented a javascript counter and upon submitting, the elapsed time is checked.
UPDATE $table_name SET end_time= IF(UNIX_TIMESTAMP(CURRENT_TIMESTAMP) - UNIX_TIMESTAMP(start_time) < $number_of_seconds, CURRENT_TIMESTAMP, '') WHERE timing_id='$timing_id'
The IF statement takes 3 parameters: the expression to be evaluated, the value if the evaluation returns true, the value if the evaluations returns false (in the above example, the value is blank - ”, which means the default field value will be inserted).