如何从不同的搜索字段输出信息?

时间:2018-12-13 21:39:08

标签: php mysql forms search

我有以下带有三个搜索字段的表格。 两个文本输入(关键字和距离)和一个下拉列表(运输)。

我的搜索功能适用于关键字文本输入,但不适用于其他两个字段。我可以看到“回显”时正在输出数据,但实际上不会搜索这些术语。

    <form action="searchresults.php" method="POST">
  <h3> Keyword </h3>
    <input type="text" name="keyword-search">

  <h3> Primary Function </h3>
  <?php
  $sql = "SELECT pf_id, primary_function FROM primary_function ORDER BY pf_id;";
  $result = mysqli_query($conn, $sql);

  echo "<select name='function-search' id = 'function-search'>";
  echo '<option value=""></option>';

  while ($row = mysqli_fetch_assoc($result)) {
                unset($id, $name);
                $id = $row['pf_id'];
                $name = $row['primary_function'];
                echo '<option value="'.$name.'">'.$name.'</option>';

              }
  echo "</select>";
  ?>

  <h3> Distance </h3>
    within <input type="text" name="distance-search"> miles of PCC
    <br>
    <button type="submit" name="submit-search">Search</button>
</form>

以下是将数据推送到的位置。

    <?php
if (isset($_POST['submit-search'])) {

$functionSearch = mysqli_real_escape_string($conn, $_POST['function-search']);
$keySearch = mysqli_real_escape_string($conn, $_POST['keyword-search']);
$distanceSearch = mysqli_real_escape_string($conn, $_POST['distance-search']);
$sql = "SELECT * FROM resource WHERE resource_name LIKE '%$keySearch%'
OR  description LIKE '%$keySearch%' OR username LIKE '%$keySearch%'
OR primary_function LIKE '%$keySearch%'
OR distance_in_miles LIKE '%$keySearch%'
ORDER BY distance_in_miles";
$result = mysqli_query($conn, $sql);
$queryResult = mysqli_num_rows($result);
// Checking for search result page errors
//echo $result;
echo $queryResult;
// echo $functionSearch;

if ($queryResult > 0){
    while ($row = mysqli_fetch_assoc($result)) {
      echo "<tr><td>". $row['resource_id'] ."</td><td>". $row['resource_name'] ."</td><td>". $row['username'] ."</td><td>". "$" .$row['cost_in_usd'] ."/". $row['cost_per'] ."</td><td>". $row['distance_in_miles'] ."</td></tr>";
    } echo "</table>";
  } else {
    echo "<br>No results matching your search";
  }
}
?>

1 个答案:

答案 0 :(得分:3)

旁注:此评论太长了。

我将删除foreach循环并改为使用单独的变量。

现在,您的foreach在每个LIKE查询中都将显示类似search1search2search3的内容,这本身不会引发错误,只会(可能)不匹配任何内容。 / p>

这里是一个示例,并将$search_x替换为您选择的条件/ POST:

$sql = "SELECT * FROM resource WHERE resource_name LIKE '%$search_1%'
        OR description LIKE '%$search_2%' OR username LIKE '%$search_3%'
        OR primary_function LIKE '%$search_4%'
        OR distance_in_miles LIKE '%$search_5%'
        ORDER BY distance_in_miles";

$result = mysqli_query($conn, $sql);
if(!$result){
   // handle no results/failure here
}

您可能还必须通过在两端,开头和/或结尾处使用一个%来解决问题。

旁注:如注释中所述,请始终对任何类型的循环函数使用适当的支撑。

顺便说一句,我建议您为此使用准备好的语句。 real_escape_string()可以绕开,这是有关此问题的问答: