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.

Lets Fill some records in the table.

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.

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.

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

Leave a Reply

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