Showing posts with label New Features of PHP 7. Show all posts

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.

Overview of PHP 7

1. What are the new features in PHP 7?

While migrating from PHP 5.6 to PHP 7, all PHP developers are so excited to know what are the new features in PHP 7. Well, PHP 7 does not disappoint anyone, here are some of the interesting new features applied in the new version.  


High performance & Consistent 64-bit support

This is the best feature that PHP 7 provides. While comparing to PHP 5.6 and HHVM 3.7, PHP7 is absolutely very fast in performance. It also provides high performance while using with frameworks and Content Management Systems(CMS).

Scalar type declaration

Scalar type declaration allows us to declare the function parameters and return the values with required data type. The return type can be any one from integer(int), string(string), floating point number(float) and boolean(bool) types.  

Return type declaration

Return type declaration specifies the data type of return value from a function, it is similar to argument type declaration.  

Null Coalesce operator

Null Coalesce operator ?? combines isset() and assignment of value, first it checks whether the variable exists or not, if it does then it takes the value, if not variable will be assigned with the second operand value. It is an interesting operator which decreases the time and long codes. 
$email =  $_GET['email' ??  'no email';



Spaceship operator

Spaceship operator <==> is used to compare two variables, it returns three values, 
-1 (less than)
 0 (equal to)
 1 (greater than)
It works with integer, floating point number and string also. 



<?php
echo <=> 1// 0
echo <=> 2// -1
echo <=> 1// 1
?>

Constant array

Constant array can be defined using define().

<?php
define
('Names', [
    
'Peter',
    
'Harry',
    
'Mary']);

echo 
Names[1]; // outputs "Harry"?>

Anonymous class

The concept of anonymous class is declaring a class within another class. For detailed information about anonymous class just visit here.

2. Why not PHP 6?

It's not like what we all think about, PHP 6 already existed and it was completely different from the new release. PHP 6 is kind of failure as it takes lot of CPU time and memory since it uses UTF-16 as default encoding.

Version 6 is failure, like PHP 6 is failure; Perl 6 is failure; MySQL 6 existed but have not been released, so this might have been a consideration.

PHP 6 project and it's features were widely known, and the current release is entirely different from that, so people would definitely be confused. This is one reason why they skipped version 6.