Building WHERE clause based on checkboxes
Let's say I have a form that has 30 checkboxes that correspond to music genres (it submits to a PHP form handler).
I have an artists table that has a genre field. What are the best practices on building a query that would behave along the lines of
Select name FROM artists WHERE genreId = 1 OR genreId = 2 OR . . . etc etc.
I know I can dynamically build my WHERE string in PHP, but I'm in the habit of using prepared statements and stored procedures. What should I do?
You can make one large query, many small ones (joining data in memory in PHP), or you can do a different concept:
- Each genre has it's own unique bit (1, 2, 4, 8, 16, ...)
- A search checks for bitwise AND of those genres vs your search mask.
A similar system (if bitwise AND not supported) would be to use a char field and compare with a regex. E.g. to be "metal" and "progressive", could be "YY", while "metal" without "progressive" would be "YN". Then regex could match only Y's.
Computer programmer / web developer.
I would use "select * from atists where genreId in ($in)", where "$in = implode(',', $_REQUEST['genreId'])". In this case the HTML code for checkboxes should look like input name="genreId" value="11", not name="genreId11" value="on". This is called array.
This worked for me. Thanks!
Originally Posted by tishetsky
Users Browsing this Thread
There are currently 1 users browsing this thread. (0 members and 1 guests)
Tags for this Thread