How To Create Autosuggest Search Box Using JavaScript in PHP/MySQL

In this tutorial, we are going to learn how to create Autosuggest Search Box Using JavaScript in PHP/MySQL. This program created using JavaScript and PHP/MySQL to show you on how to use this simple program. The user typing in a search box, it will auto-suggest the value from the database table and it will display using a drop down field. Creating simple TextBox as in the image below. Result - TextBox Here's the source code in the image above.
  1. <h2>Search Autosuggest</h1>
  2. <div id="content">
  3. <form autocomplete="off">
  4. <input type="search" name="fullname" id="name" style="width:220px;padding:10px;" placeholder="Search here..." autofocus="autofocus"/>
  5. </form>
  6. </div><br/>
Copy and paste this to your HEAD tag of your page.
  1. <script type="text/javascript" src="js/jquery.js"></script>
  2. <script type='text/javascript' src='js/jquery.autocomplete.js'></script>
  3. <link rel="stylesheet" type="text/css" href="css/style.css" />
  4.  
  5. <script type="text/javascript">
  6. $().ready(function() {
  7. $("#name").autocomplete("getresult.php", {
  8. width: 218,
  9. matchContains: true,
  10. selectFirst: false
  11. });
  12. });
Copy and paste this PHP source code and save it as "getresult.php".
  1. <?php
  2. include("dbcon.php");
  3. $search = strtolower($_GET["q"]);
  4. if (!$search) return;
  5. $sql = "select DISTINCT fullname as fullname from users where fullname LIKE '%$search%' limit 5";
  6. $query = mysql_query($sql);
  7. while($row = mysql_fetch_array($query)) {
  8. $name = $row['fullname'];
  9. echo "$name\n";
  10. }
  11. ?>
After compiling the source code above. The code above will result in the search box and drop down list shown in the picture below. Result - Autosuggest Search Box Share us your thoughts and comments below. Thank you so much for dropping by and reading this tutorial post. For more updates, don’t hesitate and feel free to visit this website more often and please share this with your friends or email me at [email protected]. Practice Coding. Thank you very much.

Comments

Submitted bycheechinho1901 (not verified)on Mon, 03/18/2019 - 10:43

hi ,thanks for your post and its working well with me,how do you display the searched contents in a table,pls help

Add new comment