This website uses cookies

Our website, platform and/or any sub domains use cookies to understand how you use our services, and to improve both your experience and our marketing relevance.

📣 Join the live AMA session with Adam Silverstein on open source and WordPress core! Register Now →

Build Live Search Box Using PHP, MySQL and AJAX.

Updated on December 8, 2021

6 Min Read
live search php mysql ajax

AJAX search refers to live search functionality, where the search engine starts to display results as you type characters in the input box. It allows you to see search results without having to load a display page. Ajax search thus makes it easier and faster for users to find what they are looking for. AJAX search is developed with JavaScript (jQuery), MySQL PHP, and AJAX.

This is how Google implements this idea on its search pages:

 

Live search is an essential aspect of UI and user experience on the website. In this article, I will highlight the process of building an autocomplete (Live Search) engine for your website.

Prerequisites:

  1. Code editor (Sublime or Notepad++ are good options)
  2. Apache and MySQL (either XAMPP or WAMP). In this article, I will use XAMPP.
  3. HTML, CSS, PHP, MySQL, Javascript, AJAX.

I will first build the script on my local machine. For this, I will need a MySQL database with sample data and connect it with the AJAX form.

Stop Wasting Time on Servers

Cloudways handle server management for you so you can focus on creating great apps and keeping your clients happy.

Database Details

Here are the details of my sample database:

Database host: localhost

Database name: autocomplete (or anything you would like to use)

Table name: search

Database user: root

Database password:

Database Setup

Open XAMPP and Start Apache and MySQL.

Now open the URL, localhost:8080/phpmyadmin (8080 is the port on my system; yours can be different)

Click on “New”.


PHP Hosting: Best PHP 7 & PHP 5.6 Web Hosting
Create a database called “autocomplete” (or anything you would like to call it).

Copy and paste the following query to create the Table (search), Column names (Id, Name), and then insert dummy data.

CREATE TABLE search (

id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,

Name VARCHAR(30) NOT NULL

);



INSERT INTO `search` VALUES

(1, 'David Copperfield'),

(2, 'Ricky Ponting'),

(3, 'Cristiano Ronaldo'),

(4, 'Lionel Messi'),

(5, 'Shane Watson');

 

The following is the output of the query:

 

Setup Files

Create the following files in htdocs folder (usually found in C:/xampp/htdocs)

Search.php (This is the main file of the search engine, where a user inputs data and views result).

db.php (This file contains database connection details).

Ajax.php (The main file that generates AJAX request to the server and returns results).

script.js (This file contains javascript functions to perform AJAX requests).

style.css ( Contains styling for the search engine).

Create Search Form and Related Files

In this step, I will create the following files:

search.php

This is the main file of the search engine, where the user inputs data and views the result. Create a file named search.php and paste the following code in it:

<!DOCTYPE html>

<html>



<head>

   <title>Live Search using AJAX</title>

   <!-- Including jQuery is required. -->

   <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>

   <!-- Including our scripting file. -->

   <script type="text/javascript" src="script.js"></script>

   <!-- Including CSS file. -->

   <link rel="stylesheet" type="text/css" href="style.css">

</head>



<body>

<!-- Search box. -->

   <input type="text" id="search" placeholder="Search" />

   <br>

   <b>Ex: </b><i>David, Ricky, Ronaldo, Messi, Watson, Robot</i>

   <br />

   <!-- Suggestions will be displayed in below div. -->

   <div id="display"></div>



</body>



</html>

db.php

This file contains the database connection details. Create a file named db.php and paste the following code in it:

 

<?php



//Database connection.

$con = MySQLi_connect(

   "localhost", //Server host name.

   "root", //Database username.

   "", //Database password.

   "autocomplete" //Database name or anything you would like to call it.

);



//Check connection

if (MySQLi_connect_errno()) {

   echo "Failed to connect to MySQL: " . MySQLi_connect_error();

}

?>

 

ajax.php

This is the main file that generates AJAX request for the server and returns the results. Create a file named ajax.php, and paste the following code in it:

<?php

//Including Database configuration file.

include "db.php";

//Getting value of "search" variable from "script.js".

if (isset($_POST['search'])) {

//Search box value assigning to $Name variable.

   $Name = $_POST['search'];

//Search query.

   $Query = "SELECT Name FROM search WHERE Name LIKE '%$Name%' LIMIT 5";

//Query execution

   $ExecQuery = MySQLi_query($con, $Query);

//Creating unordered list to display result.

   echo '

<ul>

   ';

   //Fetching result from database.

   while ($Result = MySQLi_fetch_array($ExecQuery)) {

       ?>

   <!-- Creating unordered list items.

        Calling javascript function named as "fill" found in "script.js" file.

        By passing fetched result as parameter. -->

   <li onclick='fill("<?php echo $Result['Name']; ?>")'>

   <a>

   <!-- Assigning searched result in "Search box" in "search.php" file. -->

       <?php echo $Result['Name']; ?>

   </li></a>

   <!-- Below php code is just for closing parenthesis. Don't be confused. -->

   <?php

}}


?>

</ul>

scripts.js

This file contains the Javascript functions that perform AJAX requests. Create a file named scripts.js and paste the following code in it:

//Getting value from "ajax.php".

function fill(Value) {

   //Assigning value to "search" div in "search.php" file.

   $('#search').val(Value);

   //Hiding "display" div in "search.php" file.

   $('#display').hide();

}

$(document).ready(function() {

   //On pressing a key on "Search box" in "search.php" file. This function will be called.

   $("#search").keyup(function() {

       //Assigning search box value to javascript variable named as "name".

       var name = $('#search').val();

       //Validating, if "name" is empty.

       if (name == "") {

           //Assigning empty value to "display" div in "search.php" file.

           $("#display").html("");

       }

       //If name is not empty.

       else {

           //AJAX is called.

           $.ajax({

               //AJAX type is "Post".

               type: "POST",

               //Data will be sent to "ajax.php".

               url: "ajax.php",

               //Data, that will be sent to "ajax.php".

               data: {

                   //Assigning value of "name" into "search" variable.

                   search: name

               },

               //If result found, this funtion will be called.

               success: function(html) {

                   //Assigning result to "display" div in "search.php" file.

                   $("#display").html(html).show();

               }

           });

       }

   });

});

style.css

This file contains the styling elements for the search engine. Create a file named style.css and paste the following code in it:

a:hover {

   cursor: pointer;

   background-color: yellow;

}

The search engine is now ready for testing. For this carry out the following steps:

First, open search.php by typing the following URL in the browser:

localhost:8080/search.php

Next, input some text that will be searched in the database.

 

Notice that as you type in your query, it will pass the text to script.js  that will forward this request to ajax.php file. In the ajax.php, a javascript function named “fill()” will pass the fetched results. This function will also display the result(s) into the “display” div in the  “search.php” file.

You Might Also Like: MySQL Performance Tuning Tips To Optimize Database

This is it. The Live Search box for your website is now ready to be deployed on any PHP Host for real-world traffic. If you need help with the code or would like to suggest improvements, do leave a comment below.

Host PHP Websites with Ease [Starts at $10 Credit]

  • Free Staging
  • Free backup
  • PHP 8.0
  • Unlimited Websites

TRY NOW

Q: How does Live Search Works?

A: When users are typing, the live search shows suggestions on how to complete the keyword. It might be enough to enter one character for the box to autocomplete.

Q: Why is it called Live Search?

A: One of the most convenient ways to search for specific data is the AJAX search box. It is also called live search because it reacts to the users’ input in runtime.

Q: Why choose Live Search over traditional Search Box?

A: A lot of users prefer live searches to traditional ones because of its speed and useful suggestions.

Share your opinion in the comment section. COMMENT NOW

Share This Article

Shahroze Nawaz

Shahroze is a PHP Community Manager at Cloudways - A Managed PHP Hosting Platform. Besides his work life, he loves movies and travelling.

×

Get Our Newsletter
Be the first to get the latest updates and tutorials.

Thankyou for Subscribing Us!

×

Webinar: How to Get 100% Scores on Core Web Vitals

Join Joe Williams & Aleksandar Savkovic on 29th of March, 2021.

Do you like what you read?

Get the Latest Updates

Share Your Feedback

Please insert Content

Thank you for your feedback!

Do you like what you read?

Get the Latest Updates

Share Your Feedback

Please insert Content

Thank you for your feedback!

Want to Experience the Cloudways Platform in Its Full Glory?

Take a FREE guided tour of Cloudways and see for yourself how easily you can manage your server & apps on the leading cloud-hosting platform.

Start my tour

CYBER WEEK SAVINGS

  • 0

    Days

  • 0

    Hours

  • 0

    Mints

  • 0

    Sec

GET OFFER

For 4 Months &
40 Free Migrations

For 4 Months &
40 Free Migrations

Upgrade Now