Free! - How to build a PHP Search Engine   
     Introduction or a tale of how easy a search engine could work
  Five years ago your site may have had five or six pages. However, over the time it has grown and one day you wake up with 2 GB of content, more than a thousand links and no way to sort them by relevance. You need a way for you and your visitors to get information about your services and products faster. A search engine could help you and your site visitors find that precious piece of information on your extensively growing site.
      
            



Connecting...
Now let's make the connection string. Open
  a new PHP document, name it connectionstring.php and save it in the same
  directory in which Search.php is located. For example, you can name it
  MySearchEngineWithPHP. Later on you will upload the entire folder to your
server. Add the following code to connectionstring.php:
 <?php
      $hostname_MyConnectionPHP = "localhost";
      $database_MyConnectionPHP = "database";
      $username_MyConnectionPHP = "usrname";
      $password_MyConnectionPHP = "mypassword";
      $connections =
      mysql_connect($hostname_MyConnectionPHP, $username_MyConnectionPHP,
      $password_MyConnectionPHP) or die ( "Unabale to connect to the database" );
?>
Replace "database", "usrname" and "mypassword"  with the respective data that you use for the MySQL database.
Time to search!
The following code is the core of our
  search engine. We will calculate the search time using a function, make a
  database connection with another function, and finally we will check for
  matches with an appropriate algorithm running a query to select a table to look
  for matches. Add the following code to your Search.php page:
 <?PHP
function getmicrotime()
{
    list($usec, $sec) = explode(" ",
      microtime());
    return ((float)$usec + (float)$sec);
}
$connection_string = dirname(__FILE__) . "/connectionstring.php";
require_once($connection_string);
mysql_select_db("test") or die ( 'Unable to
        select database.' );
$RESULTS_LIMIT=10;
if(isset($_GET['search_term']) &&
        isset($_GET['search_button']))
{
      $search_term = $_GET['search_term'];
    if(!isset($first_pos))
    {
        $first_pos = "0";
    }
    $start_search = getmicrotime();
    $sql_query = mysql_query("SELECT * FROM news
        WHERE MATCH(title,article) AGAINST('$search_term')");
many mathces (too many matches cause returning
        of 0 results)
    if($results = mysql_num_rows($sql_query) !=
        0)
            {
                $sql =  "SELECT * FROM news
        WHERE MATCH(title,article) AGAINST('$search_term') LIMIT $first_pos,
        $RESULTS_LIMIT";
                  $sql_result_query =
        mysql_query($sql);   
            }
    else
            {
                  $sql = "SELECT * FROM news
        WHERE (title LIKE '%".mysql_real_escape_string($search_term)."%' OR article
        LIKE '%".$search_term."%') ";
                  $sql_query =
        mysql_query($sql);
                  $results =
        mysql_num_rows($sql_query);
                  $sql_result_query =
        mysql_query("SELECT * FROM news WHERE (title LIKE '%".$search_term."%' OR
        article LIKE '%".$search_term."%') LIMIT $first_pos, $RESULTS_LIMIT ");
            }
    $stop_search = getmicrotime();
    $time_search = ($stop_search -
        $start_search);
}
?>
Let's take a closer look at the code. On the
second line we initialize function to calculate the time for the search. 
The require_once function initializes a
  connection to the database – we simply call the connectionstring.php file that
  we created earlier. With the line "mysql_select_db("test") or die ( 'Unable to
  select database.' );" we select our database table called test in our case.
  However, if for some reason a database is not selected the "die" statement will
  bring a message that a database is not able to be selected. $RESULTS_LIMIT
variable is used to specify how many results to display per page.
Next we use an "if clause" to check if any
  phrase or word is set in the search field form. This is done with
  $search_query. Then we check if our marker for page listing exists with
  $first_pos variable – if not we start from the first page. Then we need to initialize
  a SQL query – simply with $sql_query. As you may know mysql_query is a keyword
  in MySQL. Unfortunately, using that keyword has a major drawback. MySQL does
  not display results of the phrases that are found in the database too often as
  it would display too many results. That is why we do a second check. The
  algorithm counts the number of results with the $results variable and if it is
  zero we run second query with a standard field search of the table with LIKE
%...%.
 NOTE: The
  function mysql_real_escape_string is a standard MySQL function used to check if
  the entered value is legal, preventing the injection of malicious MySQL scripts
  into your database. For example, somebody could enter an SQL query in your form
  to change your database. Using mysql_real_escape_string  will make your
  search engine and database more secure.




      
Kiril Iliev started his career as a PR manager for a Bulgarian game software company and later on started working for Dynamic Zones - the company behind the zones network.
He has written a lot of articles for one of the biggest computer magazines in Bulgaria - PC Mania.
He works on various projects including PHP, CSS, and ASP scripting and is support specialist at DMXzone.com.
As of April, 2008 Kiril is acting as Research and Development Manager, researching the trends in the new technologies, especially Silverlight and LINQ implementation
See All Postings From Kiril Iliev >>
          Reviews
        
   PHP search engine
  There seems to be a problem with this search engine.  In IE when pressing enter as oppose to search button, nothing displays.  Is there any way to fix it?
         
   Paging issues
  Thanks alot for the guide, great job! Although the paging part doesn't work for me. When i select the next page i just find myself on an empty page. I haven't changed anything but the things i have to change. search.php?search_term=mysql&search_button=Search works but when i turn to the next page : search.php?search_term=mysql&first_pos=10 the page is empty. Any way to fix this problem? I have followed many search engine guides and i find this problem on every single one of them, it's getting really enoying. Maybe it's my fault some how, help would be really nice :) 
          
   ERROR!
  hello! i followed the steps that you've indicated in this *tutorial about making a search engine in php. I do all the steps including the database but when i run it, theres an error saying this  Parse error:  syntax error, unexpected T_VARIABLE in C:\Documents and Settings\Personal\Desktop\madeL\connectionstring.php on line 15 
what do you think is wrong with what ive done? pls help me coz i needed it for my thesis. plssss...
NOTE: i used POST method instead of GET method. i also used DREAMWEAVER 2004 and WAMMP. plss response. thank yoU..
       See all 7 Reviews      You must me logged in to write a review.