How to create search engine in php

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:

  • Part 1: https://youtu.be/B-ywDE8tBeQ (how to create a the simple search engine)
  • Part 2: https://youtu.be/BV3hHeGrxd8 (how to add new entries to the search engine database)

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.

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

How to create search engine in php

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 urlthat it will direct them to
  • a nice little blurbor description about what the site does
  • and the keywordsthat can be used to search for individual records

It is important to note that the id field must be set to auto incrementand 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.

How to create search engine in php

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.

$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.

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!

How to create search engine in php

Can I make a search engine in PHP?

You can easily create your own search engine in PHP. This is a text box where a user types in a term and presses the submit button and then is redirected by the search engine to the page he is looking for. For example, a user may type in the phrase, 'youtube', and then be redirected to the youtube homepage.

How can I create a search engine?

Create a search engine.
From the Programmable Search Engine homepage, click Create a custom search engine or New search engine..
In the Sites to search box, type one or more sites you want to include in the search results. ... .
In the Name of the search engine field, enter a name to identify your search engine..

How do I create a search with PHP and MySQL?

php $search = $_POST['search']; $column = $_POST['column']; $servername = "localhost"; $username = "bob"; $password = "123456"; $db = "classDB"; $conn = new mysqli($servername, $username, $password, $db); if ($conn->connect_error){ die("Connection failed: ".

How can I create a website using PHP?

To create a website using PHP, you'll need to construct three web pages. These are based upon the basic structure of header, body, and footer. As you might guess, the header includes title information. However, information for the browser is also included, such as the HTML standard in use, along with CSS references.