views:

444

answers:

3

Hello,

This question is similar to http://stackoverflow.com/questions/944158/php-multiple-dropdown-box-form-submit-to-mysql, but with a twist.

Let's assume we have an HTML multi-select, which gets submitted to a PHP backend.

How do you elegantly create a mysql request with an OR condition on the values of a multi-select?

For instance I have a multi-select with a list of sports. How do do:

SELECT * FROM sports WHERE sport.name=:sport1 OR sport.name=:sport2 OR sport.name=:sport3...
+2  A: 
SELECT * FROM sports WHERE sports.name IN ('football','hockey','soccer','trolling');
mtvee
This is a good point since I cheched mySQL operators and could not find "IN".But the question, whether using IN or ORs, is more about the PHP part to generate this from the array my input will produce. And to generate it in a elegant way, because I'm sure I can write an ugly loop with checks on first item, last item and empty array.
JB Hurteaux
+2  A: 

This is untested, just an idea...

$_POST['sports'] = array('basketball', 'baseball', 'football', 'soccer');

$sql = sprintf("SELECT * FROM sports WHERE sport.name IN (%s)", implode( ',', array_fill(1,count($_POST['sports']), '?') ) );
// SELECT * FROM sports WHERE sport.name IN (?,?,?,?) 
$st = $dbh->prepare($sql);

// bind all values
foreach( $_POST['sports'] as $i => $sport) {

    $st->bindValue( ++$i, $sport );

}

$st->execute();
Galen
Dude, if you typed that without even try it to run it, you are amazing ;-) Works perfectly.
JB Hurteaux
A: 
$_POST['sports'] = array('basketball', 'baseball', 'football', 'soccer');

$sql = sprintf("SELECT * FROM sports WHERE sport.name IN (%s)", implode(',', $_POST['sports']));

Should result in

SELECT * FROM sports WHERE sport.name IN (basketball,baseball,football,soccer)
Dratir