【发布时间】:2017-04-19 21:03:29
【问题描述】:
所以我有我的表单并想检索所有已被选中的行。 但我不能让我的 LIKE 像我想要的那样工作。它只适用于一个复选框被选中。 我想显示具有每个值的所有行。 因此,如果您勾选“Rock”和“Jazz”,它将显示所有带有“Rock”或“Jazz”的行。那些带有“Rock, Electronic”的行也会出现。
我应该有不同的方法吗?
<?php
if(isset($_POST['submit'])){
if (isset($_POST['genre'])) {
$genre_str = implode(",", $_POST['genre']);
$sql = $dbcon->prepare('SELECT * FROM user_profile WHERE user_genre LIKE :user_genre');
$sql->bindvalue(':user_genre', "%".$genre_str."%");
$sql->execute();
foreach ($sql as $row){
$row_id = htmlspecialchars($row['id']);
$row_genre = $row_post['user_genre'];
echo "id: " . $row_id . " = " . $row_genre;
echo "<br/>";
}
}
}
?>
<form action="" method="post">
<h4 class="text-center">Genre</h4>
<div class="checkbox">
<label class="checkbox-inline"><input type="checkbox" name="genre[]" value="Rock">Rock</label>
<label class="checkbox-inline"><input type="checkbox" name="genre[]" value="Funk">Funk</label>
</div>
<div class="checkbox">
<label class="checkbox-inline"><input type="checkbox" name="genre[]" value="Jazz">Jazz</label>
<label class="checkbox-inline"><input type="checkbox" name="genre[]" value="Hip-Hop">Hip-Hop</label>
</div>
<div class="checkbox">
<label class="checkbox-inline"><input type="checkbox" name="genre[]" value="Acoustic">Acoustic</label>
<label class="checkbox-inline"><input type="checkbox" name="genre[]" value="Electronic">Electronic</label>
</div>
<div class="col-md-12">
<input type="submit" name="submit" class="btn btn-block btn-success" value="Search">
</div>
</form>
【问题讨论】:
-
user_genre 中存储了哪些类型的值?单个值,还是逗号分隔的列表?
-
逗号分隔
-
Please read this. LIKE 不能为此工作,因为它会在通配符之间查找整个值,除非在 user_genre 中的某处找到该确切值,否则它将不匹配。
-
您需要遍历通过表单接收到的每个流派,并像
user_genre LIKE %:each_user_genre%一样将所有单个流派的结果推送到结果数组中,然后遍历结果数组并打印。 where 子句中 start 和 end 的 % operator 表示 start 和 end 上的任何字符串,但与您从表单中获得的字符串匹配 -
我建议为 user_genre 创建另一个表,将多个流派行映射到每个 user_profile。它将使这样的查询变得更加容易。