Create Your Own Search Engine using PHP, MySQLi and Ajax - Mostlikers

18 May, 2016

Create Your Own Search Engine using PHP, MySQLi and Ajax

In this post we are going to create our own search engine or search functionality using with PHP, MySQLi and Ajax. This is the updated post of  How To Make A Simple Search Engine Using PHP And MySQLi which i have posted in past. I received lot of positive response feedback for this topic. here I have tried to make search engine like Google.

Basic keyword search like google using php,ajax and mysqli


Live Demo            Download

Database

Create new table the using the below query. Update this table with some dummy data to check the functionality.

CREATE TABLE IF NOT EXISTS `web_information` (
        `id` int(11) NOT NULL,
          `meta_title` varchar(100) NOT NULL,
          `meta_description` varchar(300) NOT NULL,
          `site_url` varchar(300) NOT NULL
        )
        

Config.php

Database connection configuration file, here you have to modify database connection based on your local or domain phpmyadmin server.
  <?php  
         $user = 'root'; 
         $password = ''; 
         $database = '<your database>'; 
         $db=new mysqli('localhost',$user,$password,$database); 
   ?>
      

HTML Search bar

For keyword search i have used  autocomplete  jquery library.This Autocomplete widgets provides keyword suggestions based on user keywords matchcase.

While user type the keywords data will check database title by using ajax, The ajax data sucess response get the JSON format. It will replaceable to autocomplete tag.

<html>
    <head>
    <script src="//code.jquery.com/jquery-1.10.2.min.js"></script>
    <script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
    <link href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
    </head>
    <body>      
        <div class="login">
        <form action="search_result.php" id="search_form" method="GET">
            <p align="center"><img src="logos.png" /></p>
            <p><input name="q" autocomplete="off" id="list_search" type="search" required
            class="search" /></p>            
            <p align="center">
                <input type="submit" id="click" class="but" value="Mostliker search"  />
                <input type="submit"  class="but" value="I m Feeling lucky" />
            </p>            
        </form>
        </div>
    </body>
</html>

<script type="text/javascript">
$(document).ready(function(){
    $(document).on('keyup','#list_search',function(){   
        var value = $(this).val();
        $.getJSON('ajax_search_list.php?q='+value, function (data) {
            var availableTags = data;
            $( "#list_search" ).autocomplete({
                source: availableTags,
                select: function(event, ui) {
                $(event.target).val(ui.item.value);
                $('#search_form').submit();
                return false;
            },
             });
        });        
    });
});
</script>

  • $.getJSON - Load JSON-encoded data from the server using a GET request.
  • keyup - The keyup event is sent to an element when the user releases a key on the keyboard. It can be attached to any element.

Auto complete search ajax (ajax_search_list.php)

Ajax json response page. SQL result return JSON format.
<?php
include("config.php");
if(isset($_GET['q']) && $_GET['q']!="") :
    $data = mysqli_real_escape_string($db,$_GET['q']);
    $keyword =  trim(preg_replace('/\s+/',' ',$data));
    $sql=$db->query("SELECT distinct meta_title FROM `web_information` WHERE meta_title LIKE
   '%$keyword%' limit 10");
    $count=mysqli_num_rows($sql);
    if($count!=0) :
        $json_data=array();
        foreach ($sql as $key => $value):
            $json_data[] = $value['meta_title'];
        endforeach;
        echo json_encode($json_data);
    else :
        echo 0;
    endif;
endif;
?>


Keyword search result (search_result.php)

User search result page, display matching details base on user search keyword value.

<?php
include("config.php");
if(isset($_GET['q']) && $_GET['q']!="") :
    $data = mysqli_real_escape_string($db,$_GET['q']);
    $keyword =  trim(preg_replace('/\s+/',' ',$data));
    $sql=$db->query("SELECT distinct * FROM `web_information` WHERE meta_title LIKE 
    '%$keyword%' OR meta_description LIKE '%$keyword%' OR site_url LIKE '%$keyword%'");
?>
    <html>    
    <body>
    <div>
        <form action="search_result.php" id="search_form" method="GET">
            <input name="q" autocomplete="off" id="list_search" type="search" required 
            value="<?=@$keyword;?>" class="search" />
            <button type="submit"  class="but_blue">Search</button>      
        </form>
    </div>
    <div>
  <?php if(isset($sql) && count($sql) && ($sql->num_rows)) : ?>
    <div class="reslt_bar">                
        <?php foreach ($sql as $key => $search_data) : ?>
            <p><a target="_blank" href='<?=$search_data['site_url'] ?>'>
             <?=$search_data['meta_title'] ?></a><br/>
            <?=$dbContent = str_ireplace($keyword,'<b>'.$keyword.'</b>',
             $search_data['site_url']); ?></br>                       
            <?=$dbContent = str_ireplace($keyword,'<b>'.$keyword.'</b>',
             $search_data['meta_description']); ?></p>
        <?php endforeach; ?>                
    </div>
    <?php else :?>
    <p>Your search - <b><?=@$keyword;?></b> - did not match any documents.</p>        
    <?php endif; ?>
    </div>
 <?php endif; ?>
  • $sql->num_rows - Gets the number of rows in sql results.
  • LIKE %$keyword - The SQL LIKE clause is used to compare a value to similar values using wildcard operators.
  • stri_repalce -finding the match case.
  • trim () - Removing the whites ace

CSS

Add css for search textbox 
.search {
border: 1px solid #ccc;
width:572px;
min-height: 30px;
padding: 4px 20px 4px 8px;
font-size: 18px;-moz-transition: all .2s linear; 
-webkit-transition: all .2s linear;transition: all .2s linear;
}
.search:hover { 
width: 572px;
border-color:#999999;
}       
.search:focus {
width: 572px;
border-color:#03F;
outline: none;
}

This tutorial very basic level of create search engine process. We will keep update related with search engine process.  









Related Topics

13 comments:

  1. How much money you earned from this blog from starting date till today?

    ReplyDelete
    Replies
    1. Hi Jumman,

      Please comment related with your queries and suggestions.

      Delete
  2. can you please update the new version?

    ReplyDelete
  3. This comment has been removed by the author.

    ReplyDelete
  4. This comment has been removed by the author.

    ReplyDelete

  5. How can I show the number of results and pagination

    thanks

    ReplyDelete
  6. How can I show the number of results and pagination

    thanks

    ReplyDelete
  7. Hey thanks for this amazing post! I have managed to get the website running but when i type in a query it doesnt show any search results or errors. I have literally copied and pasted everything including your database. Please help me out here. thanks.

    ReplyDelete
  8. can you please update the new version (pagination number of results)?

    ReplyDelete
  9. Hello
    Dear sir,
    I am very thank you,for this script.but i have a problem
    Warning: count(): Parameter must be an array or an object that implements Countable in C:\xampp\htdocs\search_new\search_result.php on line 21.....

    my result was properly work.

    ReplyDelete