Live Search using PHP, MySQL Database and Javascript

Hello friends! We’re here again to discuss live search functionality in a dynamic website using php and javascript. Previously, we had a post on the search operation using only php. We recommend to go through it first, at here. Now, we’ll see as the data is typed, the suggestions will come under it. So, without wasting time, lets start how to do this.

Creating search takes 3 steps:

  1. Create the Database.
  2. Create live search front UI.
  3. Add the back end code.

let us see them one by one

1. Creating Database

First things first! Lets create a Database using the following query. We are creating a table ’employee’ in which id, name, email and company name data details exists.

  `id` int(11) NOT NULL,
  `name` varchar(255) NOT NULL,
  `email` varchar(100) NOT NULL,
  `company` varchar(100) NOT NULL

Lets Fill some records in the table.

INSERT INTO `employee` (`id`, `name`, `email`, `company`) VALUES
(1, 'Mike', '', 'Softglobe'),
(2, 'James', '', 'Google'),
(3, 'Mark', '', 'Microsoft'),
(4, 'Albert', '', 'Softglobe'),
(5, 'Smith', '', 'Nokia'),
(6, 'Robert', '', 'TCS'),
(7, 'Raffel', '', 'Cognizant'),
(8, 'John', '', 'Essel'),
(9, 'Peter', '', 'HP'),
(10, 'Barton', '', 'Apple');

2. Creating Live search using javascript

To make this tutorial short and easy, we have made a single file for our front end designing. It includes front UI, css and connection code. So create a file search-form.php and paste the following code in it.

<!DOCTYPE html>
<html lang="en">
<meta charset="UTF-8">
<title>Live Search using PHP, MySQL Database and Javascript</title>
<link rel="stylesheet" href="css/w3.css">
<style type="text/css">
        font-family: Arail, sans-serif;
    /* Formatting search box */
        width: 300px;
        position: relative;
        display: inline-block;
        font-size: 14px;
    .search-box input[type="text"]{
        height: 32px;
        padding: 5px 10px;
        border: 1px solid #CCCCCC;
        font-size: 14px;
        position: absolute;        
        z-index: 999;
        top: 100%;
        left: 0;
		background: white;
    .search-box input[type="text"], .result{
        width: 100%;
        box-sizing: border-box;
    /* Formatting result items */
    .result p{
        margin: 0;
        padding: 7px 10px;
        border: 1px solid #CCCCCC;
        border-top: none;
        cursor: pointer;
    .result p:hover{
        background: #f2f2f2;
<script src="js/jquery-1.12.4.min.js"></script>
<script type="text/javascript">
    $('.search-box input[type="text"]').on("keyup input", function(){
        /* Get input value on change */
        var inputVal = $(this).val();
        var resultDropdown = $(this).siblings(".result");
            $.get("backend-search.php", {term: inputVal}).done(function(data){
                // Display the returned data in browser
        } else{
    // Set search input value on click of result item
    $(document).on("click", ".result p", function(){
<div class="w3-container w3-teal">
  <h1>Live Search using PHP, MySQL Database and Javascript</h1>

<div class="w3-container">
  <p>Enter the queries to search in the search box.</p>
  <div class="search-box">
        <input type="text" autocomplete="off" placeholder="Search Employee Name..." />
        <div class="result"></div>

<div class="w3-container w3-teal">
  <p>An amazing tutorial on <a href="">Technopoints</a></p>


Make sure you have javascript files in your folder for proper working of the code. You can get them, form internet very easily. Just Google them.

We are not here using session, but you can easily implement this functionality in your session projects also.

3. Add the backend

Now, we need a special file to fetch the data from database and return it to the main file. So lets Create a file backend-search.php and add the following code in it. This is the last step to create the live search functionality.

/*connection code. Change the folowing credentials with yours.*/
    $pdo = new PDO("mysql:host=localhost;dbname=search", "root", "");
    // Set the PDO error mode to exception
} catch(PDOException $e){
    die("ERROR: Could not connect. " . $e->getMessage());
// Attempt search query execution
        // create prepared statement
        $sql = "SELECT * FROM employee WHERE name LIKE :term";
        $stmt = $pdo->prepare($sql);
        $term = $_REQUEST['term'] . '%';
        // bind parameters to statement
        $stmt->bindParam(':term', $term);
        // execute the prepared statement
        if($stmt->rowCount() > 0){
            while($row = $stmt->fetch()){
                echo "<p>" . $row['name'] . "</p>";
        } else{
            echo "<p>No results found</p>";
} catch(PDOException $e){
    die("ERROR: Could not able to execute $sql. " . $e->getMessage());
// Close statement
// Close connection

In the above file, we are using a PDO connection method for connecting with the database because it is more secure and prevents SQL injections. We have used a word “LIKE” in an SQL query to fetch the related names as we type characters in the search box.

The REQUEST super global variable is used to let the system know that the fetch operation should be started as soon as the user starts typing in the text box. the suggestions appears under the text box appears within a fraction of second.

We’ve added a styling using w3.css classes. You can get it by downloading the source code. The following image is a view of a homepage of our tutorial project.
Now visit the search-form.php file, You can directly put any employee name’s starting letter, the matching phrases will be displayed automatically. Even you can insert rows in one tab and perform fetching without refreshing the page as shown below image.

Live Search using PHP, MySQL Database and Javascript

Looking nice na? Why not try it now? The source code is always available for free of cost. You can directly download it from the below link.

Download Source Code

2 thoughts on “Live Search using PHP, MySQL Database and Javascript

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.