PHP Multiple Dropdown Box Form Submit To MySQL with OR
This question is similar to 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...
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();
SELECT * FROM sports WHERE sports.name IN ('football','hockey','soccer','trolling');
$_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)
精彩评论