简体   繁体   中英

Building an SQL query 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. 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?

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) . ')';

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM