When selecting fields in a MySQL statement you can perform certain conditional statements to get the values you require based on other values. One of these is the Switch Case conditional statement. If you’re familiar with other programming languages you probably know how to do this already but allow me to demonstrate how this can be done within a MySQL query:
SELECT CASE `field` WHEN 'value1' THEN 'output_value1' WHEN 'value2' THEN 'output_value2' WHEN 'value3' THEN 'output_value3' END AS fieldAlias FROM `table`
Heres an another example using the Switch Case conditional statement that will output a users active state based on a number in the database:
SELECT CASE `userActive` WHEN '1' THEN 'Active' WHEN '2' THEN 'Pending' WHEN '3' THEN 'Deleted' END AS userActive FROM `user`
Follow us on Twitter
Subscribe to RSS Feed
very clear example thank you , i was looking for a solution in my search.php page and instead of many if statements this just saved my life
Thanks dude. Very usefull
It was very useful, thank you!
Grettings!
wowwwwww, that is so perfect, you saved me about 200 lines of code in my website search field…thank you
Fab! just what i needed! :D