Press enter to see results or esc to cancel.


Javascript Jquery-Autocomplete textbox from values from database


In this video I have shown how we can enable auto suggestions for a textbox from MySql database.
I have shown the example in PHP as front end.

In the example the HTML form is created in index.php page, and the text box is internally calling the help of search.php to populate the auto suggestions.
The below files should be imported into the page,
1. jquery.autocomplete.js
2. jquery-1.4.2.min.js
3. style.css

index.php

<html>
<head>
 <link rel="stylesheet" type="text/css" href="style.css" />
 <script type="text/javascript" src="jquery-1.4.2.min.js"></script>
 <script type="text/javascript" src="jquery.autocomplete.js"></script>
 <script> 
 jQuery(function(){ 
 $("#search").autocomplete("search.php");
 });
 </script>
</head>
<body>
 <form action="get_form.php">
 Book Name : <input type="text" name="q" id="search" placeholder="Enter Book Name">
 <input type="submit" value="Submit"/>
 </form> 
</body>
</html>

On entering values in the textbox. Search.php is internally called for autosuggestion.

search.php

<?php
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "2017_data";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
 die("Connection failed: " . $conn->connect_error);
} 
$id = $_GET['q'];
$sql = "select book_title from book_table where book_title like '%".$id."%' limit 1";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
 while($row = $result->fetch_assoc()) {
 echo $row["book_title"]. "\n";
 }
} else {
 echo "0 results";
}
$conn->close();
?>

This page holds the code to connect to the database and call the querry for values.

get_form.php

<?php
$id = $_GET['q'];
echo $id;
?>

After submission of data. The get_form.php will show the data in the page.

index.php after running on server

auto suggestions from database

get_form.php after accepting a request from index.php