1

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...

3 Answers 3

2

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();
Sign up to request clarification or add additional context in comments.

1 Comment

Dude, if you typed that without even try it to run it, you are amazing ;-) Works perfectly.
2
SELECT * FROM sports WHERE sports.name IN ('football','hockey','soccer','trolling');

1 Comment

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.
1
$_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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.