0

I need to to do autocomplete suggestion for my thesis and the data should be retrieved from database. here is my code but it doesn't work! this is my html file.

<!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>

and this is my php file.

    <?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);
}

  ?>

I don't know why it doesn't work cause there's no error in my codes.

console errors

1 Answers1

0

mysqli_query() requires 2 arguments, the connection and the query, i.e.:

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

Warning!

Little Bobby says your script is at risk for SQL Injection Attacks. Learn about prepared statements for MySQLi. Even escaping the string is not safe!

You may want to...

Add error reporting to the top of your file(s) right after your opening <?php tag

error_reporting(E_ALL); 
ini_set('display_errors', 1);

Add error checking, such as or die(mysqli_error($connection)) to your queries and other database operations. If not, you can typically find the issues in your current error logs.

Jay Blanchard
  • 34,243
  • 16
  • 77
  • 119