PHP TutorialsWeb Developer

Make a Simple Search Engine with PHP (open source download)

Written by:

Having a search engine for your website is pretty crucial for today’s web. If your users can’t search your site for content, it is difficult to get them to see more of what you have to offer. Luckily, it’s easy and fast to create a simple search engine with PHP, HTML and a MySQL database. All with a video tutorial included! Plus the free open source download is also available here too!

Simple Search Engine How-To Video

This video tutorial on how to make a simple search engine in PHP comes in two parts:

This php tutorial has a FREE open source code download available:
Download the Source Code

Style for the Search Engine (with CSS)

For simplicity, I’m not going to focus on a how to create a fancy display for the search engine. I am just going to use a pre-made CSS stylesheet I have ready to go, named main.css. So this way we can just get into the nitty-gritty of PHP code.
(The stylesheet will be included in the source code download above).

Create the Search Engine Form

<form action="" method="GET" name="">
	<table>
		<tr>
			<td><input type="text" name="k" value="<?php echo isset($_GET['k']) ? $_GET['k'] : ''; ?>" placeholder="Enter your search keywords" /></td>
			<td><input type="submit" name="" value="Search" /></td>
		</tr>
	</table>
</form>

The important code to note from the form is all in the form attributes and the text box attributes:

  • action=”./index.php” – the form’s action is the end goal destination. This will be the location of the script that is going to do all the code crunching. For our search engine, index.php will be the only file we are working with. And because of that we will make the script send the url request back to itself.
  • method=”GET” – the GET method type is what will take the text entered into the text box and throw it into the url for the user. Like when you see “search.php?k=php+tutorial” (with the plus sign being a place holder for a space). That is a GET request being passed in the URL.
  • input type=”text” – the “text” type is simply going to do that, make the input a text input (crazy I know).
  • name=”k” – the “name” can be whatever you want it to be. Do keep in mind it is going to show in the users browser, like the example above. So usually shorter url is better.
  • value=”” – having a value of “” (blank) will make the text box always be empty when the user first sees it. It’s not really required, but it does make things a bit cleaner.
Check this out:  Fix for PHP Fatal Error: Allowed memory size error

With our style sheet and the rest of the form all setup, we see our basic search form displayed below. Pretty snazzy, ehh?

Make a Simple Search Engine - basic search form setup

Create the Search Engine Database Structure (using MySQL/phpMyAdmin)

Next we will setup the back-end SQL database structure for the search engine. Since our search engine is simple, our MySQL database will also be simple. Just a few fields to store our data. To create the database and table, I like using phpMyAdmin to manage the MySQL database backend.

Database fields we will need

The following is the list of the MySQL database fields we will end up needing for our search engine:

  • a unique id fields to easily access the information in the database
  • the title of the site the user can search
  • the url that it will direct them to
  • a nice little blurb or description about what the site does
  • and the keywords that can be used to search for individual records

It is important to note that the id field must be set to auto increment and primary key. Doing this allows for us to have an auto incrementing unique identifier for each record in the database. It also allows the queries we run against the database to be much faster.

Make a Simple Search Engine - basic database setup

Now that the front-end and database is ready, we can move onto the fun part of the actual search engine scripting. The code to operate the search engine is going to come in a few parts. First we need to get the keywords that the user searched for and format them for our use. Then we can connect to the database and run the query. And lastly we can display the search results back to the user.

Get the Search Engine Keywords

// get the search terms from the url
$k = isset($_GET['k']) ? $_GET['k'] : '';

// create the base variables for building the search query
$search_string = "SELECT * FROM search_engine WHERE ";
$display_words = "";
					
// format each of search keywords into the db query to be run
$keywords = explode(' ', $k);			
foreach ($keywords as $word){
	$search_string .= "keywords LIKE '%".$word."%' OR ";
	$display_words .= $word.' ';
}
$search_string = substr($search_string, 0, strlen($search_string)-4);
$display_words = substr($display_words, 0, strlen($display_words)-1);

We start by creating some variables that we will rely on for the script.

Start building the search query

$k – using a nested boolean statement we can make sure the url is giving us search keywords to use. Getting input from the user using this method helps with not kicking back errors for undefined variables to the user.

$search_string – we set the base of the query to be run against the database.

Check this out:  Force www or non-www in Your Website's URL with .htaccess

$display_words – just create a empty string for use later. Specifically to display a formatted version of what the user searched for back to them.

Adding each keyword to the search string

$keywords– using the explode function, we can take a normal string and turn it into an array of the same data. Using an array makes tasks like searching through a sentence word by word very easy. The first parameter is the string that you want to break at. In our case we are separating all the keywords into individual words. The next parameter is the sentence you want to break up (e.g. the $k variable).

foreach – using the foreach statement we can quickly parse each item out of the $keywords array with ease and no extra bull-crap. We are able to split each array element into a separate one. Then store it in a variable that can be worked recursively.

$search_string – we are taking each $word from the $keywords. Then formatting them into our query string that we can later search the database for. Later, using the LIKE query command we can search for strings in our database field of keywords. And by using % (percent signs) on the inside of the quotation marks, the query will search for our $word any where in the database. This is the true magic of the search engine right here!

The last two lines are just to remove the extra characters from the $search_string and $display_words variables. This helps to properly format them for the query and display back to the user.

Take a look at the MySQL query looks like

If we echo out our newly built query after searching for something such as “nickfrosty” we will see something like this:

SELECT * FROM search_engine WHERE keywords LIKE '%nickfrosty%' 

Connect to the MySQL Database and Process the Query

// connect to the database
$conn = mysqli_connect("localhost", "root", "password", "tutorials");

// run the query in the db and search through each of the records returned
$query = mysqli_query($conn, $search_string);
$result_count = mysqli_num_rows($query);

// display a message to the user to display the keywords
echo '<div class="right"><b><u>'.number_format($result_count).'</u></b> results found</div>';
echo 'Your search for <i>"'.$display_words.'"</i><hr />';

Now that we have our query built, we need to connect to the SQL server and select the database. We will go ahead and run the query string against the database. We also get the number of rows returned from doing so.

If you want to learn more about some of the php and MySQL commands and how they work, check out my tutorial here. It covers all the basics of PHP and MySQL/MySQLi operations.

Display the Search Engine Results to the User

Now that we have all of our database results we can start displaying those results to the user. For the ease of the html, we will just display them in a simple table format.

// check if the search query returned any results
if ($result_count > 0){

	// display the header for the display table
	echo '<table class="search">';
	
	// loop though each of the results from the database and display them to the user
	while ($row = mysqli_fetch_assoc($query)){
		echo '<tr>
			<td><h3><a href="'.$row['url'].'">'.$row['title'].'</a></h3></td>
		</tr>
		<tr>
			<td>'.$row['blurb'].'</td>
		</tr>
		<tr>
			<td><i>'.$row['url'].'</i></td>
		</tr>';
	}
	
	// end the display of the table
	echo '</table>';
}
else
	echo 'There were no results for your search. Try searching for something else.';

First check to make sure that there were some results returned from the database and display the results accordingly.

Check this out:  PHP basics: MySQL Database Tutorial

Using a while loop, you are able to parse through each and every one of the results returned from our search query we made earlier. The $row variable stores each individual record on each pass though of the loop. These results are stored as an associative array that we can process or display. Basically what this means is that we will be able to handle/format/display each of the results that are returned on a one-by-one basis. Each being stored in the same $row variable.

If you want to learn more about how the mysqli_fetch_assoc function works, you can check out my article on MySQL basics.

Then we can look at each of the fields of the database records by retrieving them from the associative array. For simplicity, I am just going to display each of the results in a neat table. Then let my stylesheet make them a little more pleasing to look at.

Put it all together and what do you get?

Now we have a working search engine! Below is what the will be display if you were to search for “php”. Successfully showing only the results that include the search term, just like any good search engine should!

Make a Simple Search Engine - final product

37 Replies to “Make a Simple Search Engine with PHP (open source download)”

  1. Mrinmoy says:

    Hey Nick thanks for this awesome tutorial. But the download link for the project file is not working. Could you please give a proper link to download the project file.

  2. abhishek says:

    why i am getting error in line no 70,index.php file

  3. Nad says:

    Hi Nick, I wanted to ask why the source code is very different to your youtube video on how to create a search engine. We’ve been currently trying to follow your youtube video and use the source code you provided. We keep running into errors and wish to have more guidance about the source code or the original youtube video you have made.

    • I think, the code is not different πŸ˜• may be you could check them again

      • Nick says:

        The code used to be different. I was in the process of updating the article, videos, and the source code download. They are all the same now πŸ™‚

    • Nick says:

      It depends on which video you are watching on YouTube. This source code and articles are for the updated Search Engine tutorial that I created in January 2020. Make sure you are watching the updated videos!

  4. Samer Houri says:

    as Mrinmoy
    Hey Nick thanks for this awesome tutorial. But the download link for the project file is not working. Could you please give a proper link to download the project file. Samer

    • Nick says:

      I checked the link again on my computer, and didn’t have any problems with it. What happens when you click it?

  5. Hellos Nick thanks for tutorial but i dont see the download link of source code please leave here

  6. Thank you the awesome tutorial.I am working on a music website, I want to create a search to search all the pages the user just types the artist name or song title into the search and it will return all the songs related to that artists or the specific song the user requested, off course if the song exists on my website. How can i add that functionality to your search tutorial?

    • Nick says:

      That should be pretty easy to adapt this simple search engine to do.
      First, I would create a new table for the artist. Giving it some fields like artist ID and artist name. Then create another table for albums, giving it fields like artist ID, album name, album art, release date, and any other info you want displayed.
      Next, create a table named songs with fields like album ID, song title, etc.

      Notice how each table has an ID field for the next higher part of the music hierarchy. Songs have an album ID. Albums have an artist ID. That’s how you tie all the info together in the database.
      Then in the search query string, you can search for the song titles. The song results will give you the album ID, which you can use to get all the other songs from that album or artist.

      Makes sense? (That is how I would do it)

  7. I received you reply via email, I am don’t see my comment here! But it regards a user searching all pages on my website for my song, the question is i have is, do i need to enter all the artists & songs into the Database?

    • Nick says:

      Super strange, the comment is still listed. Weird. Anyways….
      Yes, you will have to enter all of the artist and song info into the database. Unless you can find some database that you can download that already has the ones you want

  8. Joe Cardamone says:

    Hi Nick, thanks for the great tutorial. All has gone well with the coding and downloads.
    One question please, I have added a field to my table called “sort” as I wish to sort the results based on result type (eg html page v’s pdf).
    How can I introduce a sort into the code please? My attempts have been unsuccessful and the reality is I am no expert in php coding.
    Thanks,
    Joe

    • Nick says:

      Hi Joe! Good question. Are you just trying to sort the info on the page that is being displayed to the user? If so, then I would create a new $_GET variable to determine the method of sorting that the user wants. Then in the php code where you build the search query itself (the $search_string variable), add your SQL command to perform the desired type of sorting, using an if statement. So for the example of pdf files, I would write something like this:

      if ($_GET['sort'] == 'pdf')
      $search_string .= ' AND url LIKE '%.pdf' ';
      // the % sign at the beginning means the url must end with ".pdf" but can have any other text at the beginning

      On a side not, for this to work you will have to wrap the entire keywords portion of the query search string in parentheses. That is because SQL will follow an order of operations, just like math.

      So when all is said and done, your SQL query should look something like this (assuming you search for “person name” with sort of “PDF”):
      “SELECT * FROM search_engine WHERE (keywords LIKE ‘%person%’ OR keywords LIKE ‘%name%’) AND url LIKE ‘%.pdf’ “

  9. Joe Cardamone says:

    Thanks for the quick reply Nick. Can I take some more of your time to explain further please?

    My database is:
    id title url keywords Sort
    1 one Http:w hello 3
    2 two Http:x hello 1
    3 three Http:y hello 2
    4 four Http:z goodbye 1

    So if we seach on keywords “hello”, the result displayed is:

    two Http:x hello 1
    three Http:y hello 2
    one Http:w hello 3

    I do not need the user to be able to sort these results, just to display in the order I would like to.

    Hope you can assist.

    Thanks

    Joe

    • Nick says:

      Ahhh I understand what you mean. That is even easier that what I previously thought! You can use the built in SQL command “ORDER BY”.
      At the end of your $search_string, you need to add the “ORDER BY” command and then declare if you want to order ascending (aka 1,2,3 using “ASC”) or descending (aka 3,2,1 using “DESC”).

      So your SQL query should come out something like this:
      β€œSELECT * FROM search_engine WHERE (keywords LIKE β€˜%person%’ OR keywords LIKE β€˜%name%’) ORDER BY sort DESC”

      And that is it!

      • Joe Cardamone says:

        Thanks Nick, unfortunately I’m am not able to get this to work.
        My code is as per your code above, wth additional () around keywords and ORDER BY ‘sort’ at the end.

        // CHECK TO SEE IF THE KEYWORDS WERE PROVIDED
        if (isset($_GET[‘k’]) && $_GET[‘k’] != ”){
        // save the keywords from the url
        $k = trim($_GET[‘k’]);
        // create a base query and words string
        $query_string = “SELECT * FROM search_engine WHERE “;
        $display_words = “”;
        // seperate each of the keywords
        $keywords = explode(‘ ‘, $k);
        foreach($keywords as $word){
        $query_string .= ” (keywords LIKE ‘%”.$word.”%’) OR “;
        $display_words .= $word.” ORDER BY ‘sort’ “;
        }
        $query_string = substr($query_string, 0, strlen($query_string) – 3) ;

        however when I echo the $query_string I get:

        Search

        SELECT * FROM search_engine WHERE (keywords LIKE ‘%bio%’) OR (keywords LIKE ‘%sal%’)
        182 results found
        Your search for bio ORDER BY ‘sort’ sal ORDER BY ‘sort’

        Any assistance greatly appreciated.

        • Nick says:

          I think I see your issue. You added the “ORDER” command to the $display_words variable. Not the $query_string variable like you should. Try this:

          $query_string = substr($query_string, 0, strlen($query_string) – 3);
          $query_string .= ” ORDER BY ‘sort’ DESC”; // this way the ORDER command is added to the very end of the SQL query just before you run the command

          And remove the “ORDER BY” stuff from the $display_words variable inside the if statement

          • Joe Cardamone says:

            Thanks Nick, I think we are close now. I have the following code:
            $query_string = substr($query_string, 0, strlen($query_string) – 3);
            $query_string .= ” ORDER BY β€˜sort’ DESC”;
            However on the secod line, I have a “Syntax error, unexpected T_STRING”
            Any ideas please?

  10. Joe Cardamone says:

    Nixk, added space after =
    $query_string .= ” ORDER BY β€˜sort’ DESC”;
    Now all good. Thanks for your help!! Much appreciated.

  11. Godwin says:

    Thank you Nick

  12. Kayla says:

    Hello Nick,
    Thank you for this awesome tutorial and it work just fine.
    I use it for searching some content of my news table of my database .
    I would like to search also the title not only the content.
    I have this for now:
    $query_string = “SELECT * FROM news WHERE “;
    $display_words = “”;

    // seperate each of the keywords
    $content = explode(‘ ‘, $k);
    foreach($content as $word){
    $query_string .= ” content LIKE ‘%”.$word.”%’ OR “;
    $display_words .= $word.” “;
    }
    In my table news I have , id, title, content and date and I would like that the search engine work for word in the title and in the content of my news. Can you please help me for that?

    • Nick says:

      Glad you like the tutorial. You can actually do that super easy. In your “$query_string .= ….” line inside the for the foreach loop, you can just add the other database field you want the query to search for.
      $query_string .= ” content LIKE β€˜%”.$word.”%’ OR title LIKE β€˜%”.$word.”%’ OR β€œ;
      That will get the job done for you. If you want to make it so the ‘content’ and ‘title’ both have the word inside of them (and only return that result) then you can wrap the search terms inside of parenthesis and then change the middle ‘OR’ to an ‘AND’.
      Like this:
      $query_string .= ” (content LIKE β€˜%”.$word.”%’ AND title LIKE β€˜%”.$word.”%’) OR β€œ;
      Notice the specific locations of the parenthesis. The close parenthesis must be before the last ‘OR’ or else the query won’t search correctly.
      Hope this helps πŸ™‚

  13. MichelZeub says:

    Hi the form to add new entries to the search engine database dosent work

  14. Schiano Francesco says:

    Congratulations, great tutorial, I searched the net for days without ever finding an engine that didn’t kill the server and ran into memory limits, yours works great. Unfortunately I have many thousands of records and when a search finds hundreds and hundreds of results it lists them all, how could a pagination of 10 results per page be adapted? I’m not very familiar with PHP and without your help I can’t. Thank you

  15. hanelyp says:

    A great example of how NOT to program a search engine.

    You use mysqli. The newer PDO is much preferred. If you must use the older interface, at least escape the query parameters correctly to prevent SQL injection attack.

    $query_string .= ” content LIKE β€˜%”.$word.”%’ OR β€œ;
    The query constructed above is going to require a table scan, aka SLOW. There is no way to index mySQL (or to my knowledge any common database) to avoid that. It’ll work for a small database with a light load, but fail quickly as the database grows.

    • Nick says:

      You are saying a lot of true things here!

      This article was originally written about 5 years ago to show the basic idea of creating a search engine. So yes it does use MySQLi (originally written using the even older MySQL functions!) I do really need to update it for pdo, just haven’t had the time

      As I state in the article, this does not handle security at all and should not be used in a production system.

      On top of the LIKE command searching the entire database, It is true you cannot index on a LIKE command. A better use would by using MATCH.

Leave a Reply

%d bloggers like this: