使用自动完成搜索PHP的基于数据库列的记录过滤不起作用

保持编码

我在网站上集成了自动完成搜索功能,用户可以在其中输入关键字并基于该关键字查看记录。

假设,如果我编写邮政编码,则仅从zip字段中过滤数据。接下来,如果用户键入的地址类似于121 North West,那么脚本将自动选择与121 North West匹配的记录。此外,对于街道,同样,如果用户键入诸如cedar lane之类的街道名称,则它将仅从数据库字段中获取记录。

我在从所有字段中搜索记录时遇到问题,因此无法从数据库中获取正确的列表。

我关注的推荐网站是http://www.trulia.com,此处运行正常。我希望在我的网站上也可以使用,但效果不理想。

我的PHP代码:

<?php
$searchKeyword  = $_REQUEST['keyword'];

$searchQ    =   "SELECT zip, ste, st, st_num, town, addr FROM tbl_property WHERE (zip = '$searchKeyword' OR ste like '%$searchKeyword%' OR town like '%$searchKeyword%' OR addr like '%$searchKeyword%') GROUP BY zip LIMIT 0,5";
$queryRec   = mysql_query($searchQ);
$recSet     = mysql_num_rows($queryRec);
echo "<div id='fetchRecs'><ul>";
if($recSet>0){
    while($row = mysql_fetch_array($queryRec)) { 
        echo '<li>'.$row['addr'].', '.$row['town'].', '.$row['ste'].', '.$row['zip'];?></li>
    <?php
            }
        }else{
    echo "<li>No Records Found</li>";       
    }
echo "</ul></div>";

我只希望用户写123,列表显示为1234,1245,而列表类似,仅显示邮政编码列中的邮政编码。

相同,如果用户写123 cedar,则选择类似于123 cedar的列表,仅表示它将来自街道列。

PS:我只有一个文本字段,在其中输入关键字,例如:http : //www.trulia.com

附言:我的问题仍未解决,如果有人有任何有用的信息,请分享。也许它也会对其他一些东西起作用。

马蒂亚斯·皮耶罗邦(Matias Pierobon)

首先,请相信我的错误。

好的,我更改了几件事,现在可以正常工作:

//Filter:
<?php

  if (isset($_REQUEST['field']) && isset($_REQUEST['keyword'])) {
    $field = $_REQUEST['field'];
    $keyword = $_REQUEST['keyword'];
  }else{
    $field = null;
    $keyword = null;
  }
  $query = "SELECT * FROM tbl_property";
  $where = "";
  switch ($field) {
      case 'zipCode':
          $where = " WHERE zip like '" . $keyword . "%'";
          break;
      case 'addr':
          $where = " WHERE addr like " . $keyword . "%";
          break;
      case 'city':
          $where = " WHERE city like " . $keyword . "%";
          break;
  }
  $query = $query . $where;

  $db = new mysqli('localhost', 'user', 'password', 'db');
  if ($db->connect_errno > 0){
    die($db->connect_error);
  }

  $result = $db->query($query)
?>

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <title>Searcher</title>
  <link rel="stylesheet" href="">
</head>
<body>

    <section id="searcher">
      <form action="" method="post">
      <input type="text" name="keyword" id="keyword"           />
      <input type="hidden" name="field" id="field" value="all" />
      <div id="lists">
        <ul></ul>
      </div>
      </form>
    </section>

    <section id="results">
        <table>
          <caption>Results</caption>
          <thead>
            <tr>
              <th>Zip</th>
              <th>Address</th>
              <th>City</th>
            </tr>
          </thead>
          <tbody>
            <?php while($row = $result->fetch_assoc()){ ?>
            <tr>
              <td><?php echo ($row['zip']); ?></td>
              <td><?php echo ($row['addr']); ?></td>
              <td><?php echo ($row['city']); ?></td>
            </tr>
            <?php } ?>
          </tbody>
        </table>      
    </section>

    <script src="http://code.jquery.com/jquery-2.1.3.js" type="text/javascript" charset="utf-8"></script>
    <script type="text/javascript">
      $( "#keyword" ).keyup(function() {
        $.ajax({
            type: "POST",
            url: "req.php",
            data:{ key: $(this).val() },
            success: function(data){
                //Show the data to the clients
                //(in a div or a "select2" plugin)
                if (data.locations.length > 0){
                  $('#lists ul').html('');
                  $.each(data.locations, function( key, location ) {
                      //iterate over locations
                      $('#lists ul').append( '<li data-field="' + location._type + '">' + location.value  + '</li>' );
                  });

                  //SetUp hidden default value while keyword change
                  //Form the JSON Response
                  $('#field').val(data.locations[0]._type);
                }else{
                  $('#lists ul').html('No Results!');
                  $('#field').val('all');
                }
            }
        });
      });

      $('#lists ul li').click(function(){
          $('#keyword').val($(this).html());
          $('#field').val($(this).parent().data('field'));
      });
    </script>

</body>
</html>

<?php
  $db->close();
?>

//req.php
<?php
$key = $_POST['key'];

$data = array(
              'locations' => array(),
              'errors'=>array(),
              'success'=> true
              );

header('Content-Type: application/json');

  $db = new mysqli('localhost', 'user', 'password', 'db');

if($db->connect_errno > 0){
    $data['errors'][] = $db->connect_error;
    die(json_encode($data));
}

$query = "SELECT zip FROM tbl_property WHERE zip LIKE '" . $key . "%';";
$zips = $db->query($query);

$query = "SELECT city FROM tbl_property WHERE city LIKE '" . $key . "%';";
$cities = $db->query($query);

if($db->connect_errno > 0){
    $data['errors'][] = $db->connect_error;
    die(json_encode($data));
}

$index = 0;
if ($zips){
  while($row = $zips->fetch_assoc()){
      $data['locations'][] = array(
          "value"=> $row['zip'],
          "altValue"=> null,
          "display"=> $row['zip'],
          "_type"=> "zipCode",
          "propertyIndex"=> "",
          "index"=> $index
      );
      $index = $index + 1;
  }
}
if ($cities){
  while($row = $cities->fetch_assoc()){
      $data['locations'][] = array(
          "value"=> $row['city'],
          "altValue"=> null,
          "display"=> $row['city'],
          "type"=> "city",
          "propertyIndex"=> "",
          "index"=> $index
      );

      $index = $index + 1;
  }
}

$db->close();

header('Content-Type: application/json');
echo json_encode($data);

我没有对lists ul li元素上的click事件进行测试,因为我不知道您会怎么做,而这是次要的部分。

我希望那是您想要的。保持联系。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

jQuery自动完成,数据库值不起作用(Laravel 5)

使用jquery-ui自动完成搜索-不起作用

使用PHP从数据库通过mysqli从数据库检索图像不起作用

更新 derby 数据库中的记录不起作用

更新数据库记录不起作用

PHP从数据库获取数据不起作用

在PHP中使用Ajax从数据库中获取数据时,动作链接不起作用

数据库<> PHP通信脚本不起作用

PHP-从MySQL选择数据库不起作用

PHP网站表单到数据库不起作用

加载查询结果不起作用的数据库列

使用ajax的数据库更新不起作用

使用php建立数据库连接后进行修改后,它不起作用

使用PHP选择数据库中的最后一行不起作用

使用ajax,jquery和PHP从数据库更新图像不起作用

尝试检索结果时,使用PHP类连接到数据库不起作用

插入数据库不起作用

插入数据库不起作用

sqlite数据库不起作用

使用自定义搜索的ajax jQuery UI自动完成不起作用

在弹性搜索中对电子邮件使用自动完成功能不起作用

Micronaut 数据 MySQL 数据库连接自动重新连接不起作用

使用Spring使用数据库中的多列数据填充下拉框不起作用

使用基于数据库数据的自动填充选项过滤表

Java - 将记录插入数据库时,executebatch 不起作用

Flask-SQLAlchemy 更新记录方法对数据库不起作用

在wordpress中从数据库中获取记录不起作用

尽管项目存在于数据库中,但搜索不起作用

搜索我的 sql 数据库不起作用,它正在带回所有结果