在我的网站上,我有4个无线电选择器,可以为我的搜索脚本添加过滤器。如果选择了过滤器,则它应仅在过滤器设置为的列上运行搜索脚本,否则如果过滤器设置为全部或未设置,则应搜索所有列。但是,当我将我的过滤器设置为仅搜索一列(all选项有效)时,查询返回一个空结果。我测试了查询,它工作正常。 我已经发布了整个脚本的代码,但是有问题的代码块标有注释。 $ filter和$ search变量都是正确的。我已经在剧本中对此进行了测试。
<?php
include ('connect.php');
if(isset($_POST['search'])) {
$search = $_POST['search'];
if(isset($_POST['filter'])) {
$filter = $_POST['filter'];
if($_POST['filter'] == "all") {
echo "Searching all";
$query = mysqli_query($con, "SELECT DISTINCT model, image, brand, id FROM cranes WHERE (model LIKE '%$search%' OR brand LIKE '%$search%' OR type LIKE '%$search%')");
}
else {
//Code block in question starts
echo "Searching filtered selection only";
$query = mysqli_query($con, "SELECT DISTINCT model, image, brand, id FROM cranes WHERE '$filter' LIKE '%$search%'") or die(mysqli_error($con));
//Code block in question ends
}
}
else {
echo "Searching all";
$query = mysqli_query($con, "SELECT DISTINCT model, image, brand, id FROM cranes WHERE (model LIKE '%$search%' OR brand LIKE '%$search%' OR type LIKE '%$search%')");
}
}
else {
$query = mysqli_query($con, "SELECT DISTINCT model, image, brand, id FROM cranes");
}
while ($row = mysqli_fetch_array($query)) {
echo "<div class='crane'><a href='#!edit' id='" . $row['id'] . "'><img src='images/" . $row['image'] . "' /><p class='craneName'>" . $row['brand'] . ' ' . $row['model'] . "</p></a></div>";
}
?>
答案 0 :(得分:1)
$query = mysqli_query($con, "SELECT DISTINCT model, image, brand, id FROM cranes
WHERE '$filter' LIKE '%$search%'") or die(mysqli_error($con));
您已将$filter
中传递的列名称放在单引号中,这使其仅仅是文本字面而不是列名。
所以删除单引号......之后,请继续阅读SQL注入,但快速。