作为初学者,我一直在努力寻找以下情况的解决方案:
我有3张桌子:
Table 1: CITIES
id|city
1|London
2|Paris
Table 2: CATEGORIES
id|category
1|category1
2|category2
Table 3: PRODUCTS
id|city|category|name|keyword
1|1|1|product1|keyword1
2|1|1|product2|keyword2
现在我需要帮助mysql选择显示搜索结果,如下所示:
<?php
$keyword = preg_replace('#[^a-zA-Z]#', '', $_GET['keyword']);
$city = preg_replace('#[^0-9]#', '', $_GET['city']);
$category = preg_replace('#[^0-9]#', '', $_GET['category']);
$result = mysqli_query($con,"SELECT * FROM products WHERE category = '$category' AND city = '$city' AND keyword LIKE '$keyword'");
while($row = mysqli_fetch_array($result)) {
$id = $row['id'];
$name = $row['name'];
$category = $row['category'];
$city = $row['city'];
}
?>
我的网址是:search.php?keyword=keyword&category=1&city=1
这工作正常,但如果缺少任何参数,则显示0结果
sample: search.php?keyword=&category=&city=1
答案 0 :(得分:3)
你需要动态的sql生成检查示例如下:
$query = "SELECT * FROM products WHERE 1=1"; // note default case, always true
if ($category)
$query .= " AND category = ".intval($category, 10); // note intval
if ($city)
$query .= " AND city = ".intval($city, 10);
if ($keyword)
$query .= " AND keyword LIKE '%" . mysqli_real_escape_string($keyword). "%'"; // note escaping
$result = mysqli_query($con, $query);
更新:您可以使用相同的方法进行JOINS查询,请查看:
$query = "SELECT *
FROM PRODUCTS
inner join
CATEGORIES on (PRODUCTS.category = CATEGORIES.id)
inner join
CITIES on (PRODUCTS.city = CITIES.id)
WHERE 1=1";
答案 1 :(得分:1)
你这里有一个拼写错误。给城市变量添加$
符号。这应该是你没有得到任何结果的错误
$city = preg_replace('#[^0-9]#', '', $_GET['city']);
答案 2 :(得分:0)
<?php
$keyword = preg_replace('#[^a-zA-Z]#', '', mysqli_real_escape_string($_GET['keyword']));
$city = preg_replace('#[^0-9]#', '', mysqli_real_escape_string($_GET['city']));
$category = preg_replace('#[^0-9]#', '', mysqli_real_escape_string($_GET['category']);
$result = mysqli_query($con,"SELECT * FROM products WHERE category = '$category' OR city = '$city' OR keyword LIKE '%$keyword%'");
while($row = mysqli_fetch_array($result)) {
$id = $row['id'];
$name = $row['name'];
$category = $row['category'];
$city = $row['city'];
}
?>