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.
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:
$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:
list($usec, $sec) = explode(" ", microtime());
return ((float)$usec + (float)$sec);
$connection_string = dirname(__FILE__) . "/connectionstring.php";
mysql_select_db("test") or die ( 'Unable to select database.' );
if(isset($_GET['search_term']) && isset($_GET['search_button']))
$search_term = $_GET['search_term'];
$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);
$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
You must me logged in to write a review.