从数据库中检索JQuery自动完成建议

时间:2017-08-22 19:02:00

标签: php jquery

我需要为我的论文做自动填充建议,并且应该从数据库中检索数据。这是我的代码,但它不起作用!这是我的html文件。

<!DOCTYPE HTML>
<html>
<head>
<title>Fetching saved records</title>
<script src="jquery-3.2.1.js"></script>
<script src="typeahead.js"></script>
<script type="text/javascript"> </script>

 <script>
        $(document).ready(function() {

            $('input.city').typeahead({
                name: 'city',
                remote: 'samp5.php?query=%QUERY'
            });

        })
    </script>
</head>

<body>

    <form>
        Enter the name to search data:<br/>
        <input type="text" name="city" id="city" class="city"
         autocomplete="off">
            <input type="submit" name="find" id="find" value="Find Data"/>
        </form>
    </body>
    </html>

这是我的php文件。

    <?php
  include "connection.php";

  if(isset($_REQUEST['query'])) {
   $query = $_REQUEST['query'];

    $sql = mysqli_query("SELECT city, area FROM tbl_loc WHERE city LIKE '%{$query}%' OR area LIKE '%{$query}%'");
      $array = array();
    while ($row = mysqli_fetch_array($sql)) {
        $array[] = array (
            'label' => $row['city'].', '.$row['area'],
            'value' => $row['city'],
        );
    }

    echo json_encode ($array);
}

  ?>

我不知道为什么它不起作用,因为我的代码没有错误。

console errors

1 个答案:

答案 0 :(得分:1)

mysqli_query()需要2个参数,连接和查询,即:

$sql = mysqli_query($connection, "SELECT city, area FROM tbl_loc WHERE city LIKE '%{$query}%' OR area LIKE '%{$query}%'")

警告!

Little Bobby your script is at risk for SQL Injection Attacks. 了解preparedMySQLi语句。即使escaping the string也不安全!

你可能想......

在打开<?php代码

后立即将错误报告添加到文件顶部
error_reporting(E_ALL); 
ini_set('display_errors', 1);

向您的查询和其他数据库操作添加错误检查,例如or die(mysqli_error($connection))。如果没有,您通常可以在当前的错误日志中找到问题。