This tutorial will guide you through how to create a search engine for your website. The search engine will load pages of your website based on user queries. To proceed with this tutorial you will need an SQL database because to store your search results. If you use x10hosting to host your website then you will already have access to an SQL database regardless of whether you have a free or premium account.
The search engine will draw its results from an SQL database. This tutorial will cover how to create an SQL database using cPanel on x10hosting (but you can use the SQL database provider of your choice). First of all, log into your x10hosting account and open cPanel. Your view of cPanel will depend on which theme you are using. The screenshots for this tutorial are from cPanel in Paper Lantern mode. If your cPanel layout does not look like the screenshots below then you may need to switch your theme from x10Hosting Basic to Paper Lantern theme by clicking the 'Switch Theme' button pictured below.
Once in Paper Lantern mode, navigate to the section named 'MySQL® Databases'.
If you have not done so already, then we will need to create an SQL user profile to manage and access the SQL database. Navigate to the section of the webpage as indicated below and decide what username and password you would like to use. Be sure to note these details down somewhere safe because we will need them later. Part of the username will already have been filled in in the light grey box. Include this part in your notes too because it forms part of the complete username.
Now we need to create a database called 'search' using the Create New Database section of the page. Again, the first part of the database name will have been auto-filled in the grey box.
Once you have created the database, return to the main cPanel dashboard and navigate to the section named 'phpMyAdmin'.
We will use phpMyAdmin to manage the contents of our database. Navigate to the search database you created. Currently, there is nothing in the database and so we should see something similar to below.
Let's create a new table. Name the table 'search' and set it to include 5 columns. Fill in the details of those columns as shown below:
The title column will contain the name of the search engine result and the link column will contain its URL. The description column will contain all the terms which will load up the database entry when searched for. The preview column will contain a brief passage of text that will be displayed along with each search result and tells the user about the webpage the search result is linked to. Lastly, the ID column will automatically assign an identifying number to each new database entry.
Now we have created our search engine database we can begin adding some results. To do this, navigate to the 'search' table in phpMyAdmin and press the insert button which has been highlighted below.
Fill in each entry similar to the example below. You can leave the ID section blank because it will autocomplete itself when the entry is added to the database. In this example, our description is simply 'Dragon's blood tree' because we will use that as a test search term later just to see our search engine works; however, when you are creating your database entries you might like to copy and paste large sections of text from the target webpage for that search result. This will ensure when the user later comes to use your search engine that if they search for a term or phrase which can be found on a given webpage it will be included in the search results.
If you ever need to edit a database entry then you can do this by going back to the 'search' table and pressing the 'edit' button on the entry you would like to change.
The results of our searches will be displayed on a PHP: Hypertext Preprocessor (PHP) webpage. PHP is useful because it can display regular webpage content like HTML but also interact with SQL databases. The PHP page we will design will retrieve and display entries from the SQL database which match the user's query.
In your code editor, create a new PHP file and save it in the same folder as your main HTML files using the filename 'search.php'. To begin with, input into the PHP file any code you would put into a typical HTML document e.g. the contents of the head and body elements. There are one or two things you may want to tweak though. For example, you could set the title to 'Search results':
<!DOCTYPE html>
<html lang="en-GB">
<head>
<title>Search results</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" type="text/css" href="main.css">
</head>
<body>
</body>
</html>
We will now introduce into the body element the PHP code which will retrieve the results from the SQL database. First and foremost, we will need to instruct the PHP page to log in to the SQL database. An example of this code is shown below. It includes some code at the end which will display an error message if for whatever reason the connection to the SQL database fails.
<?php
$servername = "LOCALHOST";
$username = "USERNAME";
$password = "PASSWORD";
$database = "DATABASE";
$con = mysqli_connect($servername, $username, $password, $database);
if (mysqli_connect_errno()){
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
?>
Replace LOCALHOST, USERNAME, PASSWORD and DATABASE with the details of your specific SQL database. We created a username, password and database earlier and so you should already have these details. For the localhost number, you can find this by navigating to the Remote MySQL® section of cPanel and noting down the access hosts number (an example of what this number will look like is circled in red below):
Now our PHP page is connected to the SQL database, we can write the code which will retrieve the search results. The PHP code to do this is included below with comments. The code for the full PHP script without comments can be found further down the page if you want to copy and paste any of the code:
$query = mysqli_real_escape_string($con, $_GET['search']); <!––'mysqli_real_escape_string' converts any special characters like punctuation into a format that it is understandable for the SQL database. '$_GET' retrieves the user's query.––>
$up_query = htmlspecialchars($_GET['search']); <!––Converts any special characters like punctuation in the search query into HTML entities so they can be displayed as text and not interpreted as code.––>
$min_length = 2;
if(strlen($query) >= $min_length){ <!–– The SQL database will be searched if the query is at least two characters long ––>
<!––The following code will scan the description column of each entry in the SQL search database for any entries which match the user's query––>
$raw_results = mysqli_query($con,"SELECT * FROM search
WHERE (`description` LIKE '%$query%')") or die(mysqli_error());
if(mysqli_num_rows($raw_results) > 0){
echo "<h2>Search results for: $up_query</h2>";
while($results = mysqli_fetch_array($raw_results)){
$site_title=$results['title'];
$site_link=$results['link'];
$site_titlecaps=strtoupper($site_title);
$site_preview=$results['preview'];
<!––Below we display any matching search results.––>
echo "<div class='search_result'> <!––We assign the search results the class 'search_result' so we can style them––>
<h3 style='color:RoyalBlue;'><a href='$site_link' style='color:RoyalBlue;'>$site_titlecaps</a></h3> <!––This code displays the name of the search result (drawn from the title column of the SQL database) and links to the relevant webpage. The colour of the link has been set to royal blue but you can change this.––>
<article><a href='$site_link'>$site_preview</a></article> <!––A short description of the search result will be drawn from the 'preview' column of the SQL database will be displayed here and will link to the target webpage.––>
</div>";
}
}
else{
echo "<h2>NO RESULTS FOUND FOR YOUR SEARCH "$up_query"</h2>"; <!––This message will display if the search does not return any results.––>
}
}
else{
echo "<h2>Minimum search length is $min_length characters.</h2>"; <!––An error message will display if the user's query is only a single character long.––>
}
The complete PHP file should look something like this:
<!DOCTYPE html>
<html lang="en-GB">
<head>
<title>Search results</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" type="text/css" href="main.css">
</head>
<body>
<?php
$servername = "LOCALHOST";
$username = "USERNAME";
$password = "PASSWORD";
$database = "DATABASE";
$con = mysqli_connect($servername, $username, $password, $database);
if (mysqli_connect_errno()){
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$query = mysqli_real_escape_string($con, $_GET['search']);
$up_query = htmlspecialchars($_GET['search']);
$min_length = 2;
if(strlen($query) >= $min_length){
$raw_results = mysqli_query($con,"SELECT * FROM search
WHERE (`description` LIKE '%$query%')") or die(mysqli_error());
if(mysqli_num_rows($raw_results) > 0){
echo "<h2>Search results for: $up_query</h2>";
while($results = mysqli_fetch_array($raw_results)){
$site_title=$results['title'];
$site_link=$results['link'];
$site_titlecaps=strtoupper($site_title);
$site_preview=$results['preview'];
echo "<div class='search_result'>
<h3 style='color:RoyalBlue;'><a href='$site_link' style='color:RoyalBlue;'>$site_titlecaps</a></h3>
<article><a href='$site_link'>$site_preview</a></article>
</div>";
}
}
else{
echo "<h2>NO RESULTS FOUND FOR YOUR SEARCH "$up_query"</h2>";
}
}
else{
echo "<h2>Minimum search length is $min_length characters.</h2>";
}
?>
</body>
</html>
We can style our search results using the 'main.css' stylesheet:
.search_result {
color: MidnightBlue;
text-align: center;
}
The 'color' property determines what colour the text of the search results will be, while the 'text-align' property ensures the search results line up down the center of the webpage.
Now we've got our database and PHP page up-and-running, we can incorporate a search box into our webpages. The HTML code for this search box is:
<div class="search-box">
<form action="search.php" method="get">
<input type="text" name="search" maxlength="60" placeholder="Search..." required>
<button type="submit"><i class="fa fa-search"></i></button>
</form>
</div>
The opening 'div' tag should be assigned the class 'search-box' for styling purposes. The opening (<form>) and closing (</form>) form tags create an HTML form that will allow the user to input their search query. Inside the opening 'form' tag we declare action="search.php" method="get". The action attribute specifies the destination of the file which will process the form data/search query, while the method attribute determines how the form data will be sent. The 'get' method appends the form data to the url and allows the search result to be bookmarked; however, this is not very secure. If you ever have a form which processes sensitive data then the 'post' method is preferable because it appends the form data to the body of the HTTP request not the URL, thereby keeping it hidden.
The <input> tag determines what data the user can enter into the form. In this case, the input data will be a search query and so we set the 'type' to text and 'name' to search. The 'maxlength' attribute specifies how long the search query can be and the 'placeholder' determines the message that will be displayed in the search box when it is empty. Adding 'required' to the end of the 'input' tag simply means that the user must first put some text in the search box before submitting their query.
The <button> tag identifies a clickable button. Assigning the button the type 'submit' means that when the button is clicked it submits the information from the form to the 'search.php' page. The opening and closing 'i' tags have been assigned the 'fa fa-search' class. This class is a reference to a search icon which can be found in an external stylesheet we have linked to in other tutorials. If you have not done so already, then you can include a link to this external stylesheet in the head of your HTML file:
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
This stylesheet gives you access to over a thousand icons that can enhance the look of your website. A full list of these icons can be found on the publisher's website here. We will be using the search icon, which is depicted below.
Once the HTML code is in place we can style the search box by loading up our 'main.css' stylesheet again. We'll style the search box as a whole by inputting the following:
.search-box {
position: absolute;
top: 40%;
left: 22%;
}
The above code will ensure the search-box is positioned approximately in the middle of the webpage. Once that has been done we can style the button of our search box:
.search-box button {
height: 32px;
width: 32px;
margin-left: -5px;
background: LightGrey;
font-size: 17px;
border: none;
}
The height and width properties determine the size of the button. We set the 'margin-left' property to -5px so the button appears side-by-side with the search box. The 'background' peroperty determines what colour the button will be and the 'font-size' property sets how big the search icon will be. You can set the 'border' property to none if you do not want your button to have a border.
The last thing we now need to style is the text box of the search box:
.search-box input[type=text] {
height: 26px;
font-size: 17px;
width: 50vw;
}
After setting the height of the text box, we specify a font-size. This determines how large the text in the text box will be. Last but not least, we set the width of the text box. Specifying a width with the units 'vw' will allow the search box to vary in size depending on the width of the browser window. If you want a fixed search box size then simply change the units to 'px'.
And that's it! Our search engine should now be fully up-and-running. If you have been following along with the previous tutorials then the search engine should look like this when we are typing in our search (e.g. Dragon's blood tree)
Once we hit enter we will be referred to the 'search.php' and the results of our search will be displayed. In this example, the result is a link to a webpage containing photos of rare trees (such as the Dragon's blood tree!).
If you would like to do more with your search engine then you may be interested in this tutorial on how to integrate the search box into a navigation bar.
x10hosting offers free and fast web hosting as well as other extras for your website such as custom email address and SQL databases. Creating a free or premium account using this link will help support this site.