使用多个下拉菜单的PHP搜索表单过滤器

时间:2012-10-22 11:56:38

标签: php drop-down-menu filter

这是修改后的代码。仍然没有运气!请。帮助

<html>
<body>

<?php

 $mysqli = new mysqli("localhost", "root", "password", "test");

 $whereClauses = '';
 $numLocations = count($_POST['Locations']);
 $numJobs = count($_POST['Jobs']);
 $i = 0;
 if (! empty($_POST['Locations'])) {
  foreach ($_POST['locations'] as $location) {
    $whereClauses .="Locations='".mysql_real_escape_string($location)."'";
    if ($i++ == $numLocations) {
     $whereClauses .= " AND";
    }
  }
  }
  if (! empty($_POST['Jobs'])) {
  foreach ($_POST['Jobs'] as $job) {
    $whereClauses .="Jobs='".mysql_real_escape_string($job)."'";
  }
  if ($i++ == $numJobs) {
     $whereClauses .= " AND";
  }
   }
  $sql = "SELECT * FROM mytable '".$whereClauses."' ORDER BY id DESC '".$limit."'";

$result=mysql_query($sql);

while ($row = mysql_fetch_array($result)) {
echo $row['Locations'];
echo $row['Jobs'];
}

?>
 </body>
</html>

=============================================== 我创建了一个HTML和PHP文件,用于根据多个下拉过滤器过滤Web表单数据。这是形式。当我运行表单和PHP时,我在浏览器中看不到任何结果。也没有错误。我正在研究另一个论坛成员发布的示例。 请帮忙。提前致谢。

<form action="showJobs_new.php" method="post">
<select name="Locations">
<option value="" selected="selected">All Locations</option>
<option value="arizona">Arizona</option>
<option value="alaska">Alaska</option>
</select>
<select name="Jobs">
<option value="" selected="selected">All jobs</option>
<option value="Carpenter">Carpenters</option>
<option value="Plumbers">Plumbers</option>
</select>
<input type="submit" value="search jobs" />
</form>

showJobs_new.php:

<html>
<body>

<?php

$username="root";
$password="password";
$database="test";

mysql_connect(localhost,$username,$password);
@mysql_select_db($database) or die( "Unable to select database");

$whereClauses = array(); 
if (! empty($_POST['Locations'])) $whereClauses[] ="Locations='".mysql_real_escape_string($_POST['Locations'])."'"; 
if (! empty($_POST['Jobs'])) $whereClauses[] ="Jobs='".mysql_real_escape_string($_POST['Jobs'])."'"; 
$where = ''; 
if (count($whereClauses) > 0) { $where = ' WHERE '.implode(' AND ',$whereClauses); } 

$sql = mysql_query("SELECT * FROM mytable ORDER BY id DESC $limit" .$where);  

$result=mysql_query($sql);
or die("Error: ".mysql_error()."<br />Query: ".$sql);

while ($row = mysql_fetch_assoc($result)) {
echo $row['Locations'];
echo $row['Jobs'];
}

?>
</body>
</html>

2 个答案:

答案 0 :(得分:3)

将查询更改为

$sql = mysql_query("SELECT * FROM mytable " .$where." ORDER BY id DESC $limit");  

查询的顺序似乎是错误的。

答案 1 :(得分:1)

亲爱的你在查询中有两个错误。

1 - 这是因为你提出错误的条款顺序。您需要了解查询中子句的优先级。运行查询时,子句的顺序应该类似于

  • 选择

  • 其中

  • 分组

  • 订购BY

  • 限制

2-使用mysql_query两次user1599669

的建议

所以你的查询应该是

 $sql = mysql_query("SELECT * FROM mytable $where ORDER BY id DESC $limit");

有关更多参考,请参阅mysql dev

相关问题