我有一个多重复选框搜索查询,用于从数据库中提取数据。以下是代码:
HTML code:
<form action="search.php" method="post">
<input type="checkbox" name="cloth_color[]" value="Red" /> Red <br>
<input type="checkbox" name="cloth_color[]" value="Yellow" /> Yellow <br>
<input type="checkbox" name="cloth_color[]" value="Blue" /> Blue <br>
<input type="checkbox" name="cloth_color[]" value="Green" /> Green <br>
<input type="checkbox" name="cloth_color[]" value="Magenta" /> Magenta <br>
<input type="checkbox" name="cloth_color[]" value="Black" /> Black <br>
<input type="checkbox" name="cloth_color[]" value="White" /> White <br>
<input type="submit" value="SEARCH">
</form>
PHP代码:
<?php
$checkbox1 = $_POST['cloth_color'];
$chk="";
foreach($checkbox1 as $chk1)
{
$chk .= $chk1;
}
if($_POST['cloth_color'] != "") {
$query = "SELECT * FROM clothings WHERE colorofcloth = '$chk'";
$result = mysql_query($query);
while($row = mysql_fetch_array($result)) {
$colorofcloth = $row['colorofcloth'];
echo 'The cloth with ' . $colorofcloth . ' color';
echo '<br>';
}
}
?>
现在如果我从搜索选择框中选择一个选项,我就会得到查询。但如果我选择两种或更多颜色,我就不会得到查询。非常感谢帮助。
P.S。我在Mysql查询中确实有多个连接,但这是我被困的地方,因此在这里提出尽可能清晰的问题。此外,我打算在启动此代码之前将mysql转换为mysqli。谢谢:))
答案 0 :(得分:0)
<?php
$checkbox1 = $_POST['cloth_color'];
$chk="";
foreach($checkbox1 as $chk1)
{
$chk .= $chk1 . ",";
}
if($_POST['cloth_color'] != "") {
$query = "SELECT * FROM clothings WHERE colorofcloth IN($chk)";
$result = mysql_query($query);
while($row = mysql_fetch_array($result)) {
$colorofcloth = $row['colorofcloth'];
echo 'The cloth with ' . $colorofcloth . ' color';
echo '<br>';
}
?>
你可以试试这个代码,它将使用MySQL的IN(),你可以传递多个分开的值。
希望这有帮助
答案 1 :(得分:0)
您可能想要使用的是Mysql IN CLause。
对于此示例,我假设您对de IN子句中的元素使用了正确的语法。
如果选择红色和蓝色,正确的语法将是您需要用逗号分隔的所有值。
$chk = 'red, blue'
使用&#39; IN条款&#39;这个查询
$query = "SELECT * FROM clothings WHERE colorofcloth = '$chk'";
应该转变为此。
$query = "SELECT * FROM clothings WHERE colorofcloth IN ('$chk')";
我对PHP知之甚少,但对于数据库,它应该可以工作。
让我知道它是否有效。
答案 2 :(得分:0)
好的,这就是我做的。首先得到了@Dhaval和@Carlos的大力帮助,因为我不熟悉Mysql中的IN函数。
<?php
$checkbox1 = $_POST['cloth_color'];
$chk="";
foreach($checkbox1 as $chk1)
{
$chk .= "'" . $chk1."', ";
//This is important as it is not the number it is a word so it should have a single quote if in query we are using double quote or vice versa.
}
$check_e = rtrim($chk,", ");
//Although i havn't checked in real time if mysql query will take last comma or not but it is a good practice to remove the last comma by rtrim.
if($_POST['cloth_color'] != "") {
$query = "SELECT * FROM clothings WHERE colorofcloth IN($check_e)";
$result = mysql_query($query);
while($row = mysql_fetch_array($result)) {
$colorofcloth = $row['colorofcloth'];
echo 'The cloth with ' . $colorofcloth . ' color';
echo '<br>';
}
?>