Live Search in php with Ajax and Mysql

A search engine has become a useful tool in today’s internet world. It is very helpful for developers, testers, managers, and other internet users. Using this we can get the information on any topic of our choice. In this article, we will talk about creating our own search engine with the help of PHP, MySQL, and Ajax. Our goal is not to replace the big giants e.g. Google, Yahoo, etc but to give a good attempt in order to have our own search engine. In this article, we will talk about the basics of search engines and then see how to develop our own search engine using PHP, MySQL, and Ajax.

Download below two files

Html code

<link href="https://scripts.guru/front/js/jquery-ui.css" rel="Stylesheet"></link>
<script src="https://scripts.guru/front/js/jquery-ui.js"></script>

<input type="text" name="search" id="txtinput" />

Jquery code

function split( val ) {
            return val.split( /,\s*/ );
    }
    function extractLast( term ) {
             return split( term ).pop();
    }

 $( "#txtinput" ).bind( "keydown", function( event ) {
         if ( event.keyCode === $.ui.keyCode.TAB && $( this ).data( "autocomplete" ).menu.active ) {
             event.preventDefault();
         }
 }).autocomplete({
         source: function( request, response ) {
             $.getJSON( "search.php",{
                 term: extractLast( request.term )
             },response );
         },
         search: function() {
             // custom minLength
             var term = extractLast( this.value );
             if ( term.length < 1 ) {
                 return false;
             }
         },
         focus: function() {
             // prevent value inserted on focus
             return false;
         },
         select: function( event, ui ) {
             var terms = split( this.value );
             // remove the current input
             terms.pop();
             // add the selected item
             terms.push( ui.item.value );
             // add placeholder to get the comma-and-space at the end
             terms.push( "" );
             this.value = terms.join( "" );
             return false;
         },
         position: {  collision: "flip"  }
 });

In above code to call in search.php file

define('DB_SERVER', "localhost");
define('DB_USER', "root");
define('DB_PASS', "");
define('DB_DATABASE', "blog");
$con = mysqli_connect(DB_SERVER, DB_USER, DB_PASS, DB_DATABASE);
$value  = $_GET['term'];
$data = array();
$sql = mysqli_query($con, "SELECT * FROM tbl_post WHERE title like '%".$value."%' ");
while ($row = mysqli_fetch_assoc($sql))
{
    $data[] = array(
            'label' => $row['title'],
            'value' => $row['title']); 
}
echo json_encode($data);

Now, finally run encode.

Leave a Reply

Your email address will not be published. Required fields are marked *