ArtsAutosBooksBusinessEducationEntertainmentFamilyFashionFoodGamesGenderHealthHolidaysHomeHubPagesPersonal FinancePetsPoliticsReligionSportsTechnologyTravel

Tutorial: How to Create/Make your own search engine using PHP and MySql as Database without algorithm - For your Website

Updated on October 3, 2013

In this tutorial, You will learn "How to build your own search function" for allowing your visitors to search through your site via a Html search form or Button. Here, we are using php language and MySql database services to develop this functionality and is recommended to clear the basic concepts about both before reading more. I unexpectedly developed this when I'm helping one of my colleague and friend in completing his college assignment, So, I will provided you here with the most basic code you can use to do this task. You can also do this task in other languages but in that also you need to know the raw (most basic) sql queries and how to implement them in a particular language.

I suppose you know the basics of Structered query language and are already using them in your codes that were written for your site. So here's the first HTML code to create a search button and form to accept user input and query.

How to create basic search engine using php and mysql
How to create basic search engine using php and mysql
<form method="get" action="search.php">
<label>Search For: </label><input type="text" name="query" />
<input type="submit" name="submit" value="Start Search" />
<input type="reset" value="Reset"
</form>
Search form or button
Search form or button

Paste the above code anywhere in your page within the body tag and can customize it's look via CSS. Now, here is the snippet of php code that will retrieve results from MySql database and I'm sure you never assumed this to be so easy. Save this code on another page with name "search.php" in the same directory or you can do changes as per your requirement. Here,

  • $_GET['query'] fetches or decodes the data provided via form from any webpage using 'GET' method as a parameter value of url or webpage address,

<?php
// Change the fields below as per the requirements
$db_host="Host Name";
$db_username="Username used to access database";
$db_password="Password to access database";
$db_name="Database u created for site";
$db_tb_name="Name of the table u created in site database";
$db_tb_atr_name="attribute(column name) of table in which search action is to be performed";

//Now we are going to write a script that will do search task
// leave the below fields as it is except while loop, which will display results on screen

mysql_connect("$db_host","$db_username","$db_password");
mysql_select_db("$db_name");

$query=mysql_real_escape_string($_GET['query']);

$query_for_result=mysql_query("SELECT * FROM $db_tb_name WHERE 

$db_tb_atr_name like '%".$query."%'");
echo "<h2>Search Results</h2><ol>";
while($data_fetch=mysql_fetch_array($query_for_result))
{
	echo "<li>";
	echo substr($data_fetch[$db_tb_atr_name], 0,160);
	echo "</li><hr/>";
}
echo "</ol>";

mysql_close();
?>

You can also perform search task on multiple columns of table in this way

$query_for_result=mysql_query("
				SELECT * FROM table_name WHERE 
				Column_1 like '%".$query."%' 
				OR 
				Column_2 like '%".$query."%' 
");

Basics of Code snippet doing the search task on database you created for your website:

  1. We are storing the changeable values in variables defined at the top of script,
  2. Then, we are connecting and selecting the database we created for our site,
  3. Then, we are executing the mysql query using mysql_query() function on a particular column name (attribute) of table in our site database. Note: We are using the '%' sign on both side of '$query' variable in 'WHERE' condition of mysql query to find the matching queried word in a sentence or in between a big word stored in our database.
  4. Then, we are running 'while loop' condition to fetch all the rows containing the giving word till the last check and we are printing them on screen simultaneously using echo command.
  5. Then, at last after the work is completed, we are closing the connection with database for the stability and security purposes.
  6. Finally, the conclusion is "Script presented here contains nothing but an extra '%' and 'LIKE' commands in query which does the work of searching as according to the needs of most basic search engine with only one algorithm".

To Make it Work on Single Page (Section Added on 15:30 IST 22-09-2011)

If You think that creating two separate pages for both PHP Script and HTML form is little lengthier and frustrating task, then, here is the solution of it. You can copy and paste code shown below in a single page and it does not require extra modifications, other than those explained above. You can still make it work via other pages after setting the action attribute of HTML form pointing to this page.

You can Clearly see in PHP script below, We are using the isset() function of PHP, Simultaneously with "IF" PHP statement to check submission of form. If form is submitted, then, PHP Code will execute or vice versa.

<form method="get" action="">
<label>Search For: </label><input type="text" name="query" />
<input type="submit" name="submit" value="Start Search" />
<input type="reset" value="Reset"
</form>

<?php
//PHP CODE STARTS HERE

if(isset($_GET['submit'])){

// Change the fields below as per the requirements
$db_host="Host Name";
$db_username="Username used to access database";
$db_password="Password to access database";
$db_name="Database u created for site";
$db_tb_name="Name of the table u created in site database";
$db_tb_atr_name="attribute(column name) of table in which search action is to be performed";

//Now we are going to write a script that will do search task
// leave the below fields as it is except while loop, which will display results on screen

mysql_connect("$db_host","$db_username","$db_password");
mysql_select_db("$db_name");

$query=mysql_real_escape_string($_GET['query']);

$query_for_result=mysql_query("SELECT * FROM $db_tb_name WHERE 

$db_tb_atr_name like '%".$query."%'");
echo "<h2>Search Results</h2><ol>";
while($data_fetch=mysql_fetch_array($query_for_result))
{
	echo "<li>";
	echo substr($data_fetch[$db_tb_atr_name], 0,160);
	echo "</li><hr/>";
}
echo "</ol>";

mysql_close();
}
?>

Now, Dhadam!!!!!! - You created your first search engine and can start developing algorithms to output most useful/related results on users screen with a better look.

working

This website uses cookies

As a user in the EEA, your approval is needed on a few things. To provide a better website experience, hubpages.com uses cookies (and other similar technologies) and may collect, process, and share personal data. Please choose which areas of our service you consent to our doing so.

For more information on managing or withdrawing consents and how we handle data, visit our Privacy Policy at: https://corp.maven.io/privacy-policy

Show Details
Necessary
HubPages Device IDThis is used to identify particular browsers or devices when the access the service, and is used for security reasons.
LoginThis is necessary to sign in to the HubPages Service.
Google RecaptchaThis is used to prevent bots and spam. (Privacy Policy)
AkismetThis is used to detect comment spam. (Privacy Policy)
HubPages Google AnalyticsThis is used to provide data on traffic to our website, all personally identifyable data is anonymized. (Privacy Policy)
HubPages Traffic PixelThis is used to collect data on traffic to articles and other pages on our site. Unless you are signed in to a HubPages account, all personally identifiable information is anonymized.
Amazon Web ServicesThis is a cloud services platform that we used to host our service. (Privacy Policy)
CloudflareThis is a cloud CDN service that we use to efficiently deliver files required for our service to operate such as javascript, cascading style sheets, images, and videos. (Privacy Policy)
Google Hosted LibrariesJavascript software libraries such as jQuery are loaded at endpoints on the googleapis.com or gstatic.com domains, for performance and efficiency reasons. (Privacy Policy)
Features
Google Custom SearchThis is feature allows you to search the site. (Privacy Policy)
Google MapsSome articles have Google Maps embedded in them. (Privacy Policy)
Google ChartsThis is used to display charts and graphs on articles and the author center. (Privacy Policy)
Google AdSense Host APIThis service allows you to sign up for or associate a Google AdSense account with HubPages, so that you can earn money from ads on your articles. No data is shared unless you engage with this feature. (Privacy Policy)
Google YouTubeSome articles have YouTube videos embedded in them. (Privacy Policy)
VimeoSome articles have Vimeo videos embedded in them. (Privacy Policy)
PaypalThis is used for a registered author who enrolls in the HubPages Earnings program and requests to be paid via PayPal. No data is shared with Paypal unless you engage with this feature. (Privacy Policy)
Facebook LoginYou can use this to streamline signing up for, or signing in to your Hubpages account. No data is shared with Facebook unless you engage with this feature. (Privacy Policy)
MavenThis supports the Maven widget and search functionality. (Privacy Policy)
Marketing
Google AdSenseThis is an ad network. (Privacy Policy)
Google DoubleClickGoogle provides ad serving technology and runs an ad network. (Privacy Policy)
Index ExchangeThis is an ad network. (Privacy Policy)
SovrnThis is an ad network. (Privacy Policy)
Facebook AdsThis is an ad network. (Privacy Policy)
Amazon Unified Ad MarketplaceThis is an ad network. (Privacy Policy)
AppNexusThis is an ad network. (Privacy Policy)
OpenxThis is an ad network. (Privacy Policy)
Rubicon ProjectThis is an ad network. (Privacy Policy)
TripleLiftThis is an ad network. (Privacy Policy)
Say MediaWe partner with Say Media to deliver ad campaigns on our sites. (Privacy Policy)
Remarketing PixelsWe may use remarketing pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to advertise the HubPages Service to people that have visited our sites.
Conversion Tracking PixelsWe may use conversion tracking pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to identify when an advertisement has successfully resulted in the desired action, such as signing up for the HubPages Service or publishing an article on the HubPages Service.
Statistics
Author Google AnalyticsThis is used to provide traffic data and reports to the authors of articles on the HubPages Service. (Privacy Policy)
ComscoreComScore is a media measurement and analytics company providing marketing data and analytics to enterprises, media and advertising agencies, and publishers. Non-consent will result in ComScore only processing obfuscated personal data. (Privacy Policy)
Amazon Tracking PixelSome articles display amazon products as part of the Amazon Affiliate program, this pixel provides traffic statistics for those products (Privacy Policy)
ClickscoThis is a data management platform studying reader behavior (Privacy Policy)