In this tutorial, we are going to Build Ajax Search Box using PHP as core language. Ajax Search booms the usage of web projects such as one Google uses. Searching through Ajax and also maintaining less load on Server is a big challenge.

10 April, 2018: Updated the PHP5 Code to PHP7.


I have already posted about Ajax Search Box in Node, we are replacing Node back-end script with PHP. Format of data coming from Server is JSON itself. We will call the Search web service using GET request.

Database Design:

Open up your PHPMyadmin and create database of any name. Inside that database execute following query.

CREATE TABLE 'user_name'
    user_id INT(20) PRIMARY KEY,
    first_name TEXT

Put some dummy data in it using INSERT command.

Designing Front-end :

I am using Twitter typeahead JavaScript library to perform Ajax call to PHP file. It’s neat and clean library specially designed for this kind of purpose. Just add the path to HEAD section and you are good to go.

    <title>Ajax Search Box using PHP and MySQL</title>
    <script src="">        </script>
     <script src="typeahead.min.js"></script>
     <input type="text" name="typeahead">

In above code we have designed the front-end of our app. CSS codes are available in Download package.

Calling PHP Script Using GET

Next task is to call our PHP script when user type in the text box. Since we are doing this using typeahead library we can do this using following.

        name: 'typeahead',
        limit : 10

It automatically fetch text box value in %QUERY variable.

Retrieving data from MySQL and returning as JSON:

Here goes the main task. In PHP file first, we have to fetch the GET value which stored the search parameter. Then we have to form a connection to MySQL database and fire query to get a relevant result.

Once the result is been fetch, we have to pack it in JSON format and return back to front-end to display it as result.

    $array = array();
    $query=mysqli_query($con, "select * from cfg_demos where title LIKE '%{$key}%'");
      $array[] = $row['title'];
    echo json_encode($array);

Kindly change the parameter according to your database and column details.

Running the code :

If you have downloaded the project source code, then create database of any name and table using code shown above and simply update those information in Search.php

Place the project folder in ‘htdocs‘ directory and access it using localhost/foldername.