Wednesday, December 17, 2008

Usage of IF condition in mysql

Scenario:

Suppose we have the field in the table lets say status which has the ENUM value ACTIVE,INACTIVE.Usually after getting the value of this field(through the query)

we used to write return ($result['status']=='ACTIVE')?1:0 in class methods.

Here we are getting the db result array and based on the check(ACTIVE/INACTIVE) we are returning the boolean value.Instead of that we can have that check in the query itself like below

SELECT IF(status='ACTIVE',1,0) AS statuscheck from table1

Note that in the condition we need to give single equal symbol

so the code return ($result['status']=='ACTIVE')?1:0 will be replaced by return $result['statuscheck'].

No comments: