条件搜索基于TextField和列表菜单

时间:2011-02-28 16:08:55

标签: php mysql

我正在尝试进行搜索,用户可以根据特定条件搜索某些场所(夜总会)。

截至目前,我已经设置了一个搜索框,用户可以输入俱乐部名称和列表菜单来选择位置。

下拉列表菜单(从数据库动态生成)如下:

位置:

Select
Westlands
Eastleigh
Langata
Kamukunji
Dagoretti
Starehe 
Makadara

我想这样做,如果用户将文本字段留空并选择westlands并点击搜索按钮,那么westlands的所有俱乐部都会显示出来。 This is working fine.

此外,用户可以在文本框中输入内容并将列表菜单保留为默认选择,并显示匹配结果。 This is working fine too.

我还希望当用户在文本框中输入“P”并选择westlands时,所有以字母“P”开头的westlands俱乐部都会显示出来。 This is not working.

我的代码:

//get textfield search value
$search_value = "-1";
if (isset($_POST['event_search'])) 
{
  $search_value = $_POST['event_search'];
  $search_value = mysql_real_escape_string($search_value);
}

//get location search value
$location_search_value = "-1";
if (isset($_POST['location'])) 
{
  $location_search_value = $_POST['location'];
  $location_search_value = mysql_real_escape_string($location_search_value);
}

//query establishments table
mysql_select_db($database_connections, $connections);
$query_establishment = "SELECT establishment_id, establishment_thumb_url, establishment_name, establishment_pricing, location_name
FROM establishment JOIN location ON establishment.location_id = location.location_id WHERE (establishment_name LIKE '".$search_value."%' 
AND establishment.location_id = '$location_search_value') OR (establishment_name LIKE '".$search_value."%' 
OR establishment.location_id = '$location_search_value')";
$establishment = mysql_query($query_establishment, $connections) or die(mysql_error());
$totalRows_establishment = mysql_num_rows($establishment);

截至目前,当我在文本框中输入“P”并选择westlands时,所有以字母P开头的俱乐部都会显示,无论位置如何。我该如何解决这个问题?

穆乔欣赏任何帮助。

2 个答案:

答案 0 :(得分:1)

你的where子句中有一些奇怪的东西。

如果您测试:(A和B)或(A或B)

A => a.establishment_name LIKE '".$search_value."'
B => a.location_id = '".$location_search_value."'

如果A是真的,则不需要b为真。这说明你的第三个例子不起作用。我认为您应该根据您的解释测试您的值并创建正确的WHERE子句。

if($search_value != "" && $location_search_value == "") {
    $where = "a.establishment_name LIKE '".$search_value."'";
} else if ($search_value == "" && $location_search_value != "") {
    $where = "a.location_id = '".$location_search_value."'";
} else {
    $where = "(a.establishment_name LIKE '".$search_value."' AND a.location_id = '".$location_search_value."')";
}
$query = "SELECT a.*, b.location_name ".
         "FROM establishment a ".
         "JOIN location b ON a.location_id = b.location_id ".
         "WHERE ".$where; 

答案 1 :(得分:0)

查询中有错误。您正确插入了$search_value,但是您在第二个变量上使用了不带.的单引号。试试这个:

$query = "SELECT a.*, b.location_name
  FROM establishment a JOIN location b ON a.location_id = b.location_id
  WHERE (a.establishment_name LIKE '".$search_value."' AND a.location_id = '".$location_search_value."')
  OR (a.establishment_name LIKE '".$search_value."' OR a.location_id = '".$location_search_value."')";