Search engine with drop down suggestion using PHP and AJAX



Hello developers, in this post we are going to create a search engine with drop down suggestion. The languages we are going to use are,

  • HTML
  • CSS
  • JavaScript
  • PHP 
  • SQL

The relational DBMS we are using is MySQL.

Files used:

  1. Search.html
  2. searchScript.js 
  3. search_DB.php
  4. config.php

Database details

  1. Username = "root"
  2. Password = ""
  3. Database name = "SearchData"
  4. Table Name = "Users"
  5. Table Columns = id, names, ages
In this example, we are searching the NAMES from database, when we search by typing the keyword in the search box, it automatically suggests the existing names form the table "USERS". The structure of the database looks like,

How does it work

When you type a keyword in your HTML file, it triggers a JavaScript function (using onkeyup event). JavaScript function now sends a request to PHP file by sending the keyword you have entered through URL. PHP file gets the keyword and executes a SELECT query and retrieve the requested data from MySQL database. The retrieved data will be sent to JavaScript file as a response, now well we got the data to be displayed. JavaScript does that job too, yes it displays result in the div below the search input box.

Create a table in database

Open up localhost/phpmyadmin and create a table with multiple number of rows in VARCHAR type. Our database table would look like

Let's start coding

HTML file (Search.html)

Create an input box, style the input box with your favorite design. Put a small <div> below the input box to show the suggestions. Since it is a simple CSS coding we are not creating a separate CSS file.

<html>  
 <head>  
  <script language="JavaScript" src="searchScript.js"></script>  
  <style>  
  <!--CSS CODES -->  
  a{  
   text-decoration: none;  
  }  
  input{  
   width: 400px;  
   height: 50px;  
   font-size: 30px;  
   padding-left: 20px;  
   border: none;  
   outline: none;  
   box-shadow: inset 0px 0px 4px rgba(18, 18, 18, 0.4);  
   font-family: roboto thin;  
   border-radius: 15px;  
  }  
  #filter{  
   width: 400px;  
   max-height: 200px;  
   border: 0px solid black;  
   display: none;  
   color: black;  
   padding-top: 0px;  
   overflow-y:scroll;  
   overflow-x: hidden;  
  }  
  li{  
   width: 100%;  
   height: 50px;  
   list-style: none;  
   margin: 0px;  
   font-size: 20px;  
   color: grey;  
   line-height: 50px;  
   font-family: roboto black;  
   text-align: left;  
   padding-left: 20px;  
  }  
  li:hover{  
   background: lightgrey;  
   color: white;  
  }  
  ul{  
    width: 100%;  
   margin: 0px;  
   position: relative;  
   left: -40px;  
  }  
  </style>  
 </head>  
 <body ><br><br><br><br><br>  
 <center>  
  <input type="text" id="userInput" placeholder ="Search" onkeyup="process()"><br>  
  <div id="filter"></div> <!--Div to display drop down suggestion -->  
 </center>   
 </body>  
 </html>  

Our Html page will look like,

JavaScript File (searchScript.js)

 /* While using AJAX, it is necessary to create a different object for Internet Explorer, otherwise IE browser won't support. It is shown in below coding.  
 */  
 var xmlHttp = createXmlHttpRequestObject();  
 // Create XML Http Request object  
 function createXmlHttpRequestObject(){  
  var xmlHttp;  
 // For Internet Explorer   
  if(window.ActiveXObject){  
  try{  
   xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");  
  }catch(e){  
   alert("can't create IE object");  
   xmlHttp = false;  
  }  
  }else{  
 //For Google Chrome and other  
  try{  
   xmlHttp = new XMLHttpRequest();   
  }catch(e){  
   xmlHttp = false;   
  }  
  }  
  if(!xmlHttp){  
  alert("can't create that object!");  
  }  
  else{  
  return xmlHttp;  
  }  
 }  
 //function which gets triggered on the event onkeyup in search box  
 function process(){  
 if(xmlHttp.readyState == 4 || xmlHttp.readyState == 0){  
  filter = document.getElementById('filter').style.display="block";  
  //Store the keyword form the search box in a variable  
  userInput = encodeURIComponent(document.getElementById("userInput").value);  
  /*Send the request, make sure you give 3 parameters  
 1-Method, 2- url, 3- true or false   
 */  
  xmlHttp.open("GET", "searchDB.php?userInput="+userInput, true);  
 //set the function which takes care of response  
  xmlHttp.onreadystatechange = handleResponse;  
  xmlHttp.send(null);  
  }else{  
  }  
 }  
 function handleResponse(){  
  if(xmlHttp.readyState == 4 || xmlHttp.readyState == 0){  
  if(xmlHttp.status == 200){  
   xmlResponse = xmlHttp.responseText;  
   document.getElementById("filter").innerHTML = xmlResponse;  
  }else{  
   alert("something went wrong");  
  }  
  }  
 } 

MySql Configuration file (Config.php)

<?php
 
 $host = "localhost";
 
 $user = "root";
 
 $password = "";
 
 $db = "searchData";
 
 $conn = mysqli_connect($host, $user, $password, $db);
 if(mysqli_connect_errno()){
  echo "Connection error : ". mysqli_connect_error();
 }
?>

PHP file (searchDB.php)

<?php
//include the database configuration file

include('config.php');
//Check whether userInput exists or not

  if(isset($_GET['userInput'])){
   $value = $_GET['userInput']; //assign the value
  }else{
   echo "no input";
  }
//Select query

  $sql = "SELECT names FROM users WHERE names LIKE '%".$value."%';";
  if($result = mysqli_query($conn, $sql)){
   if(mysqli_num_rows($result) > 0){ 
//Store the result in an array list[]

     while($row = mysqli_fetch_array($result)){
     $list[] = $row['names'];
    }
   }else{
//set a null value to list[] if no result to prevent error

    $list[] = "";
   }
  }
 
  if(!empty($value)){
   if($matched = preg_grep('~'.$value.'~', $list)){
   $count = 0;
   echo '<ul>';
    while($count < sizeOf($list)){
     if(isset($matched[$count])){
/*
link the real target search file which should be opened when we click the search button or select the one from the drop down suggestion.
*/
      echo '<a href=target_file.php?searchItem='.$matched[$count].'><li>'.$matched[$count].'</li></a>';
     }
     $count++;
    }
   echo '</ul>';
   }else{
    echo "No result";
   }
  }
?>

Whohoo! We have done creating the search engine with suggestion drop down. Now it's time to see the output.



 Thanks for reading my post, I hope you had learnt something. Thank you!
Please like and share.

Jefinson O

I'm a PHP developer, I'm so interested to share something with people what I learn today. Blogging is my Hobby and I love doing it. Google

2 comments:

  1. Hello :) How can I embed this to my blog? I'm using Blogger~ If it is alright to use your codes, Thank you!

    ReplyDelete
  2. it really helped. thanks
    can you help me with displaying the items related to the keyword from database?
    using GET method?

    ReplyDelete