如何组合搜索框和下拉列表以输出结果(php,mysql)


How to combine a search box and dropdown to output results (php, mysql)

我创建了一个带有搜索框和美国50个州的下拉列表的HTML表单。 我想要的是让用户在搜索框中输入关键字(电子邮件、主题、用户名等(,然后从下拉列表中选择一个状态。 通过从下拉列表中选择一个状态,我希望我的 PHP 代码仅在该选定状态下从搜索框中找到关键字。 例如,作为用户,我想在华盛顿州找到"足球"并查看结果列表。

换句话说,如何仅显示所选状态与搜索表单相结合的结果?

这是我的一些PHP代码,让大家了解我想要完成的任务。

// this is pulling the text that was typed in the html search box
$searchbox = $_POST['searchbox'];
// this is pulling the state from my HTML drop down menu
$state = $_POST['state'];
$searchboxresult = mysql_query("
  SELECT *
  FROM   table
  WHERE (ID      LIKE '%".$_POST['searchbox']."%')
     OR (stateID LIKE '%".$_POST['searchbox']."%')
     OR (city    LIKE '%".$_POST['searchbox']."%')
     OR (subject LIKE '%".$_POST['searchbox']."%')
     OR (email   LIKE '%".$_POST['searchbox']."%')
     OR (posting LIKE '%".$_POST['searchbox']."%')
     OR (skill   LIKE '%".$_POST['searchbox']."%')
     OR (event   LIKE '%".$_POST['searchbox']."%')
     OR (days    LIKE '%".$_POST['searchbox']."%')
     OR (url     LIKE '%".$_POST['searchbox']."%')
");
// and
$statedropdownresult = mysql_query("
  SELECT * FROM table WHERE stateID LIKE '%$state%'
");

然后我有一个 while 循环来搜索所有内容并输出数据。 但是我无法让状态下拉以限制用户正在搜索的内容。 我只能让一个或另一个mysql_query与我的 while 循环结合使用,而不是两者兼而有之。 出于某种原因,使用 AND 将查询合并为一个似乎也不起作用。有什么想法吗?

我知道代码很草率并且存在安全问题,但是我稍后会进行清理。 如果您需要更多细节或澄清某些事情,我很乐意详细说明!

你可以

尝试这样的事情:-

$sql ="SELECT * FROM table WHERE 1";
if($_POST['searchbox'] != ''){
     $sql =" and (ID LIKE '%".$_POST['searchbox']."%') OR (stateID LIKE              
     '%".$_POST['searchbox']."%') OR (city LIKE '%".$_POST['searchbox']."%') OR   
     (subject LIKE '%".$_POST['searchbox']."%') OR (email LIKE  
     '%".$_POST['searchbox']."%') OR (posting LIKE '%".$_POST['searchbox']."%') OR  
     (skill LIKE '%".$_POST['searchbox']."%') OR (event LIKE  
     '%".$_POST['searchbox']."%') OR (days LIKE '%".$_POST['searchbox']."%') OR (url  
     LIKE '%".$_POST['searchbox']."%')";
}
if($state != ''){
    $sql .= " and stateID LIKE '%".$state."%'";
}
  mysql_query($sql);

希望这有帮助。