我有一个搜索页面,其中包含一个表单,用户可以在其中设置2个不同字段(名称和城市)的值。它工作正常,但对于这两个领域,用户可以选择" ANY"当他们只想要那个城市的结果时,作为一个选项。但如果他们选择ANY,他们将得到0结果,因为我的查询是AND查询。我无法弄清楚如何构造此查询,以便它显示两个值的结果,或者仅为一个值,如果他们为第二个字段选择ANY。 我无法使用" OR"因为他们可能也希望在城市中获得特定名称的结果。 允许所有选项的最佳查询是什么?
<?
//Connection
$name = $_GET['name'];
$city = $_GET['city'];
$link = mysqli_connect($dbhost, $dbuser, $dbpass) or die('MySQL
error:'.mysql_error());
mysqli_select_db($link, $dbname) or die('MySQL error:'.mysql_error());
$query = "(SELECT * FROM people where name='$name' and city='$city')";
$result = mysqli_query($link, $query);
$num_rows = mysqli_num_rows($result);
echo "$num_rows Rows\n";
echo "<table border='1'>
<tr>
<th>School</th>
<th>City</th>
</tr>";
/* fetch associative array */
while ($row = mysqli_fetch_assoc($result)) {
echo "<tr>";
echo "<td>" . $row['name'] . "</td>";
echo "<td>" . $row['city'] . "</td>";
echo "</tr>";
}
/* free result set */
mysqli_free_result($result);
echo "</table>";
mysqli_close($link);
?>
答案 0 :(得分:2)
试试这个:
$query = "(SELECT * FROM people where (name='$name' or '$name' = 'ANY') and (city='$city' or '$city' = 'ANY')";
对不起,这是任何一个周围的报价。试试这个:
$query = "(SELECT * FROM people where (name='$name' or '$name' = \'ANY\') and (city='$city' or '$city' = \'ANY\')";
-OR -
$query = "(SELECT * FROM people where (name='$name' or '$name' = \\\'ANY\\\') and (city='$city' or '$city' = \\\'ANY\\\')"
取决于可能正在进行的其他任何逃避行为。
还要注意代码注入,希望这些用户输入的字符串已经使用mysqli_real_escape_string()等内容进行了转义。
我希望这会有所帮助。
答案 1 :(得分:0)
请尝试以下方法:
$query = "(SELECT * FROM people where name = case '$name' when 'ANY' then name else '$name' end and city= case '$city' when 'ANY' then city else '$city' end)";
答案 2 :(得分:0)
请查看此演示并转换为php代码
http://rextester.com/live/XSPV71393
SELECT
*
FROM mytable
WHERE name_ LIKE (CASE
WHEN @searchname = 'any' THEN '%%'
ELSE concat('%', @searchname, '%')
END)
AND city LIKE (CASE
WHEN @searchcity = 'any' THEN '%%'
ELSE concat('%', @searchcity, '%')
END);
所以php代码应该是下面的
$query = "SELECT * FROM mytable WHERE name_ LIKE (CASE WHEN ".$name." = 'any' THEN '%%' ELSE concat('%', ".$name.", '%') END) AND city LIKE (CASE WHEN ".$city." = 'any' THEN '%%' ELSE concat('%',".$city"., '%') END);";