Reputation: 258
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. Where the genreId's are chosen from checkboxes.
I know I can dynamically build my WHERE clause in PHP, but I'm in the habit of using prepared statements and stored procedures. What should I do?
Upvotes: 0
Views: 1386
Reputation: 71384
You would likely want to use IN()
in your where clause like this:
WHERE genreId IN (1,2,3)
Unfortunately, there really isn't a good solution to use this in a parameterized way. You just have to go old-school:
$query = 'SELECT ... WHERE genreId IN (' . implode(',', $genreId_array) . ')';
I suppose though you could do something like this to build a parametrized approach:
$query = 'SELECT ... WHERE genreId IN (';
$array_length = count($genreId_array);
for ($i = 0; $i < $array_length; $i++) {
$query .= '?,';
}
$query = rtrim(',',$query) . ')';
Upvotes: 2