简体   繁体   中英

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...
SELECT * FROM sports WHERE sports.name IN ('football','hockey','soccer','trolling');

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

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