This tutorial will show you how to create a search engine that allows users to search the content on your website. To complete this tutorial you will require a database to store the search results. You should be able to create a database easily if you chose a hosting provider that offers access to cPanel, as recommended in our tutorial on registering your website.
The search engine will draw results from a SQL database. This tutorial will assume your web hosting provider offers access to 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 change your theme to Paper Lantern theme by clicking the 'Switch Theme' button pictured below.
Once in Paper Lantern mode, navigate to the section called '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. To do this, navigate to the Add New User section and enter the username and password you would like to use. Be sure to note these details down somewhere safe because you will need them later. Part of the username may 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.
Next, navigate to the Create New Database section and create a database called search. Again, a preceding part of the database name may be auto-filled in the grey box.
Once you have created the database, return to the main cPanel dashboard and navigate to the section called phpMyAdmin.
We will use phpMyAdmin to manage the search engine database. First, we need to create a table to store the search engine results. To do this, navigate to the search database. The database should be empty, as shown below.
Let's create a new table. The table will be called Results and will comprise five columns, each containing a different item of information about the search results. To create the results table, click the SQL tab then copy and paste the following SQL code into the text box:
CREATE TABLE Results (
ID int NOT NULL AUTO_INCREMENT,
Title varchar(255),
URL varchar(255),
Description varchar(255),
Preview varchar(255),
PRIMARY KEY (ID)
);
The above SQL code creates a table called Results that comprises the following columns:
Once you have pasted the SQL code into the text box, press the Go button to run the code and create the Results table. You should see a confirmation message that the table was successfully created.
Let's now add search results to the database. To do this, navigate to the Results table in phpMyAdmin and click the Insert tab, as shown below.
Fill in each field with the details of the search result. You can leave the ID field blank because the database will automatically assign a unique ID value. In the below screenshot, the search result description is simply "Dragon's blood tree" because we will use that as a test search term later to confirm the 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. Providing as much useful text as possible in the description field will help ensure the record is returned in response to the user's search query.
If you ever need to edit a database entry then you can do this by returning to the Results table and pressing the edit button for the record you would like to change.
Search results will be displayed on a PHP (PHP: Hypertext Preprocessor) web page. PHP is a server-side scripting language, which allows you to perform actions on the server that your website is hosted on. The results of these actions can be displayed to the user. In this instance, we will use PHP to query the search database and retrieve relevant results that we can show to the user. You can add HTML code to PHP files and build web pages in the usual way, just with the added functionality of PHP.
In your code editor, create a new PHP file and save it in your website's root directory (the same directory as your website's homepage) using the filename search.php. To begin, add the regular HTML code you would add to a typical web page. For example, you should define the head and body elements, as shown below:
<!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>
Next, we'll write the PHP code that connects to the database. To do this, add the following code to the body element:
<?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();
exit();
}
// Retrieve the search results here
?>
In the above code, replace LOCALHOST, USERNAME, PASSWORD and DATABASE with the details of your database. You set up a username, password and database in the section on creating the search database 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):
Once the PHP file has connected to the database, we can retrieve the search results. To do this, replace the // Retrieve the search results here comment in the PHP script with the following code:
if (isset($_GET['search'])) {
$param = "%{$_GET['search']}%";
$query = mysqli_prepare($con, "SELECT * FROM Results WHERE Description LIKE ?");
mysqli_stmt_bind_param($query, "s", $param);
mysqli_stmt_execute($query);
$results = mysqli_stmt_get_result($query);
$rows = mysqli_num_rows($results);
mysqli_stmt_close($query);
if ($rows > 0) {
echo "<h2>Search results for: {$_GET['search']}</h2>";
while ($result = mysqli_fetch_array($results)) {
$result_title=$result['Title'];
$result_url=$result['URL'];
$result_preview=$result['Preview'];
echo "<div class='search_result'>
<h3><a href='$result_link'>$result_title</a></h3>
<article><a href='$result_url'>$result_preview</a></article>
</div>";
}
} else {
echo "<h2>No results found for your search: {$_GET['search']}</h2>";
}
} else {
echo "<h2>No search query provided. Please try your search again.</h2>";
}
mysqli_close();
The user's search query will be appended to the web page URL. In the above code, we retrieve the search query using PHP's GET command. If no search query is provided, then a message will be printed to the web page asking the user to submit their query again. Meanwhile, if the PHP code successfully retrieves the user's search query, then it wraps the query string in percentage symbols (%). The percentage symbols indicate that one or more characters can appear before or after the user's search query when we search the database for suitable matches. This step is important because it means search results will be returned even if the user only enters a fragment of an entries Description field in the Results database table.
Next, we prepare the SQL query that will search the Records table for entries that contain the user's search query somewhere in their description. It is important to never add PHP variables directly to the SQL query string because hackers can manipulate the variables using SQL injection and access your database. For this reason, the above code instead prepares the query then binds the user's search query parameter later. Preparing and binding SQL queries introduces extra validation steps and ensures the SQL query has not been manipulated by hackers.
If the user's search query returns results from the database, then the PHP script will extract the information from each result and add it to the web page. Meanwhile, if no results are found then a message will advise the user accordingly.
To begin styling the search results, it would be a good idea to add the following CSS code to your main.css stylesheet:
.search_result {
color: MidnightBlue;
text-align: center;
}
.search_result a {
color: RoyalBlue;
}
The above code styles the text colour and text alignment of the text and links in each search result.
Now we've got our database and PHP script up-and-running, we can incorporate a search box into the web page. The HTML code for this search box is included below:
<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 that processes sensitive data then the post method is preferable because it appends the form data to the body of the HTTP request and 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 element means that it is not possible to submit the form unless the input field contains a value.
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 the HTML code:
<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.
To style the search box, you could add the following code to your main.css stylesheet:
.search-box {
position: absolute;
top: 40%;
left: 22%;
}
The above code will position the search box in the centre of the web page. You can position the search box elsewhere if you prefer.
.search-box button {
height: 32px;
width: 32px;
margin-left: -5px;
background: LightGrey;
font-size: 17px;
border: none;
}
The above code styles the search button. It defines the height and width of the button and sets the left margin to -5px. This margin value helps ensure the button appears beside the search box. Meanwhile, the background property determines what colour the button will be and the font size property sets how big the search icon will appear. You can set the 'border' property to none if you do not want your button to have a border.
You can also style the search box:
.search-box input[type=text] {
height: 26px;
font-size: 17px;
width: 50vw;
}
The above code defines the height and width of the search box and the font size of the displayed text. Specifying a width with the units vw means the search box to vary in size depending on the width of the browser window. If you want a fixed search box size then use px units instead.
And that's it! Your 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 the 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.