Tutorial: Ajax search with MySQL, PHP and JQuery.

In this tutorial, I will show you how to create an Ajax search form using JQuery, PHP and MySQL. For the purposes of this tutorial, I will be creating an Ajax form that allows the user to search a database of employee names.

Our MySQL database.

We will start off by creating our employees table in MySQL:

  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `name` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
  PRIMARY KEY (`id`)

The above SQL statement will create a simple table called employees. There are only two columns. The id column, which is a simple auto_increment primary key column and name, which is a VARCHAR column that will contain the employee’s name.

Let’s insert some test data so that we can search our MySQL database:

INSERT INTO `employees` (`id`, `name`) VALUES
(1, 'Michael Doyle'),
(2, 'Sandra Jones');

Feel free to add more employee names to the table if you wish.

Our Ajax HTML form.

Here is a simple Ajax search form that was built using HTML and JavaScript. Be sure to read the comments if you want to fully understand what is going on:

<!DOCTYPE html>
<html lang="en">
    <meta charset="UTF-8">
    <title>Ajax MySQL search with PHP and JQuery</title>
    <!-- Text input to enter the employee's name -->
    <input type="text" id="employee_name"><br>
    <!-- Our search button -->
    <input type="button" id="search_button" value="Search">
    <!-- This div will contain a list of all employee names that match our search term -->
    <div id="search_results" style="padding:5px;"></div>

<!-- JQuery library -->
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
    //Add a JQuery click listener to our search button.
        //If the search button is clicked,
        //get the employee name that is being search for
        //from the search_box.
        var employee_name = $('#employee_name').val().trim();

        //Carry out a GET Ajax request using JQuery
            //The URL of the PHP file that searches MySQL.
            url: 'search.php',
            data: {
                name: employee_name
            success: function(returnData){
                //Set the inner HTML of our search_results div to blank to
                //remove any previous search results.
                //Parse the JSON that we got back from search.php
                var results = JSON.parse(returnData);
                //Loop through our employee array and append their
                //names to our search results div.
                $.each(results, function(key, value){
                    //The name of the employee will be present
                    //in the "name" property.
                    $('#search_results').append(value.name + '<br>');
                //If no employees match the name that was searched for, display a
                //message saying that no results were found.
                if(results.length == 0){
                    $('#search_results').html('No employees with that name were found!');

Here is how the form above works:

  1. The user enters an employee name into the text input field and clicks on the search button.
  2. Once the search button is clicked, our JQuery event handler carries out an Ajax request to search.php, which is where our PHP code will be located. The name that was entered into the text input field is sent to our PHP script via a GET parameter called “name”.
  3. Our PHP script searches our MySQL database and returns any matching results.
  4. As soon as the Ajax request has been completed successfully, we loop through the results and append them to a div.
  5. If no employees match that name, we display a message to the user.

Obviously, you can change things around and spruce up the appearance of the form. However, for the purpose of this tutorial, I am trying to keep things extremely simple.

Our PHP search script.

In this PHP script, we connect to MySQL using PDO and return any results that match the user’s search query. Be sure to pay attention to the comments.


//MySQL username.
$dbUser = 'root';

//MySQL password.
$dbPassword = '';

//MySQL host / server.
$dbServer = 'localhost';

//The MySQL database your table is located in.
$dbName = 'test';

//Connect to MySQL database using PDO.
$pdo = new PDO("mysql:host=$dbServer;dbname=$dbName", $dbUser, $dbPassword);

//Get the name that is being searched for.
$name = isset($_GET['name']) ? trim($_GET['name']) : '';

//The simple SQL query that we will be running.
$sql = "SELECT `id`, `name` FROM `employees` WHERE `name` LIKE :name";

//Add % for wildcard search!
$name = "%$name%";

//Prepare our SELECT statement.
$statement = $pdo->prepare($sql);

//Bind the $name variable to our :name parameter.
$statement->bindValue(':name', $name);

//Execute the SQL statement.

//Fetch our result as an associative array.
$results = $statement->fetchAll(PDO::FETCH_ASSOC);

//Echo the $results array in a JSON format so that we can
//easily handle the results with JavaScript / JQuery
echo json_encode($results);

In the code above, we:

  1. Connect to our MySQL database using PDO.
  2. We execute a prepared statement that selects rows from our employees table. In this particular example, we are using a LIKE clause with two wildcard operators. This is so that search queries such as “Jones” will return results such as “Sandra Jones”.
  3. Any rows that match the user’s search query are returned as an associative array.
  4. We convert our associative array into a JSON format and print it out.
  5. If no matches are found, $results will be an empty array.

Hopefully, you found this tutorial to be simple and straight-forward. If there are parts of this tutorial that you do not understand, then I suggest that you read the following articles, as they may help to fill any gaps in your knowledge (you may be trying to run before you can walk):