Question

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...
Was it helpful?

Solution

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();

OTHER TIPS

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)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top