这个问题类似于PHP Multiple Dropdown Box Form Submit To MySQL,但有一个转折。
假设我们有一个HTML多选,它将被提交给PHP后端。
如何在多选的值上优雅地创建带有OR条件的mysql请求?
例如,我有一个带有运动列表的多选。 怎么做:
SELECT * FROM sports WHERE sport.name=:sport1 OR sport.name=:sport2 OR sport.name=:sport3...
答案 0 :(得分:2)
SELECT * FROM sports WHERE sports.name IN ('football','hockey','soccer','trolling');
答案 1 :(得分:2)
这是未经考验的,只是一个想法......
$_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();
答案 2 :(得分:1)
$_POST['sports'] = array('basketball', 'baseball', 'football', 'soccer');
$sql = sprintf("SELECT * FROM sports WHERE sport.name IN (%s)", implode(',', $_POST['sports']));
应该导致
SELECT * FROM sports WHERE sport.name IN (basketball,baseball,football,soccer)