PHP - AJAX Live Search

In this tutorial you will learn how to create or implement a simple live MySQL database search feature using the PHP and Ajax.

Ajax Live Database Search

You can create a simple live database search feature utilizing the Ajax and PHP, where the search results will be displayed as you start typing some character in search input box. In this tutorial we're going to create a live search box that will search the countries table and show the results asynchronously. But, first of all we need to create this table.

Live search has many benefits compared to traditional searching:

  • Results are shown as you type
  • Results narrow as you continue typing
  • If results become too narrow, remove characters to see a broader result
  • Example -

    Creating the Database Table

    After creating the table, you need to populate it with some data using the SQL INSERT statement. Alternatively, you can download the prepopulated countries table by clicking the download button and import it in your MySQL database.

    Creating the Search Form

    Now, let's create a simple web interface that allows user to live search the names of countries available in our countries table, just like an autocomplete or typeahead. Create a PHP file named "search-form.php" and put the following code inside of it.

    Example -

    Processing Search Query in Backend

    And here's the source code of our "backend-search.php" file which searches the database based on query string sent by the Ajax request and send the results back to browser.

    Example -