PHP Ajax Live Search

Here I explain how to develop PHP Ajax Live Search feature with help of MySQL database. Actually Live Search is mandatory for our every project because then only able to get relevant data from database side. So here we are creating simple example which is get data from MySQL, if data is not found then it showing No results found message. Totally there is three options are here implemented in this example.

The first method is without database we have to store data from option value in select dropdown with search text box. Every values are showing in the particular field when we are typing the first letter. For that first we have to add the plugin on select 2. This is one of the best alternative for get data without communicate into server side. Select2 helps to add search box, data set, tagging, infinite scrolling and more features are available.

Select2

Let’s start how to install and setup Select2 on your existing or new projects. First open the official website of Select 2 website and then add the following CDN (Content Delivery Network) for integrate in our source code. After that only it will be initialized and executed on our project.

Installation

Add these two lines of code on your <head> section.

<link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />
<script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>

They are officially give us two options like one is CDN and another one is Bower. If you are develop projects on Core then use CDN otherwise if you are using framework such as Laravel, Angular, React, Django then go for second option of composer. Moreover we have collection of PHP exercises and source code in free of cost.

Sample Code

For the example purpose here I have add the simple code and try on your computer. I get following output results which is visible on next of code section.

<html>
<head>
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.6-rc.0/css/select2.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.6-rc.0/js/select2.min.js"></script>
<style>.custom-select2{width:300px;}</style>
</head>
<body>
<script>
$(document).ready(function() {
    $('.js-example-basic-single').select2();
});
</script>


<select class="js-example-basic-single" name="state">
   <option value="AL">Select Name</option>
  <option value="AL">Vetri Selvan</option>
  <option value="WY">Jeya Bashkaran</option>
  <option value="AL">Vetrivel Pandian</option>
  <option value="WY">Jeya Priya</option>
  <option value="WY">Jeya Sinthiya</option>
</select>

Output Screenshot

Once check the output for how select option values are displayed locally from client side without interact into server side database.

select 2 ajax live search

select 2 search php

select 2 no results found

PHP & MySQL Ajax Live Search from Database

Suppose the first method is not suitable for you ? then just leave and follow this one but here we are not adding any submit feature like get data from database when click submit button. It’s just works like get relevant name from MySQL table. Next article I will share like how add search select box drop down value with textbox from MySQL database. Which is used for get filtered information only from customer search queries.

So first create one simple file and add following below code. Already I told select dropdown not works on this example. In the most of tutorial people’s are looking for how add search box in option value in PHP code. Alternatively you can use datalist for add the search fields on your project.

input list="browsers" class="form-control" name="product-category" /></label>
<datalist id="browsers">
<?php  foreach ($all_categories as $cat): ?>
                      <option value="<?php echo (int)$cat['id'] ?>">
                        <?php echo $cat['name'] ?><!--</option>-->
                    <?php endforeach; ?>
                    </datalist>

In the above code the category name will be fetch data from server side. If you are get data in static format then you can add option value to search and display the values. This is one the best alternative for select drop down textbox search fields.

<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script>
$(document).ready(function(){
    $('.search-box input[type="text"]').on("keyup input", function(){
        /* Get input value on change */
        var inputVal = $(this).val();
        var resultDropdown = $(this).siblings(".result");
        if(inputVal.length){
            $.get("data.php", {term: inputVal}).done(function(data){
                // Display the returned data in browser
                resultDropdown.html(data);
            });
        } else{
            resultDropdown.empty();
        }
    });
    
    $(document).on("click", ".result p", function(){
        $(this).parents(".search-box").find('input[type="text"]').val($(this).text());
        $(this).parent(".result").empty();
    });
});
</script>
    <div class="search-box">
        <input type="text" autocomplete="off" placeholder="search terms" />
        <div class="result"></div>
    </div>
data.php

<?php
$link = mysqli_connect("localhost", "root", "", "inventory1");
if($link === false){
    die("ERROR: Could not connect. " . mysqli_connect_error());
}
if(isset($_REQUEST["term"])){
    $sql = "SELECT * FROM products WHERE name LIKE ?";
    if($stmt = mysqli_prepare($link, $sql)){
        mysqli_stmt_bind_param($stmt, "s", $param_term);
        $param_term = $_REQUEST["term"] . '%';
        if(mysqli_stmt_execute($stmt)){
            $result = mysqli_stmt_get_result($stmt);
            if(mysqli_num_rows($result) > 0){
                while($row = mysqli_fetch_array($result, MYSQLI_ASSOC)){
                    echo "<p>" . $row["name"] . "</p>";
                }
            } else{
                echo "<p>No Results found</p>";
            }
        } else{
            echo "ERROR: Could not execute $sql. " . mysqli_error($link);
        }
    }
    mysqli_stmt_close($stmt);
}
mysqli_close($link);
?>

Demo – Screenshots – PHP AJAX Live Search

I have add just three products only for sample purpose, you can add more data when you take it on real time scenario projects.

php mysql search value

Leave a Reply