Use the CASE method as described in the link you provided, but build the query dynamically with the values you want.
Likely, this will be built with a for loop similar to how you're already doing it, but you will end up with a single query rather than querying your database every iteration.