Tutorial: How to Create your own search engine using Php and MySql Database - For your Website
By itech
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.
<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>
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:
- We are storing the changeable values in variables defined at the top of script,
- Then, we are connecting and selecting the database we created for our site,
- 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.
- 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.
- Then, at last after the work is completed, we are closing the connection with database for the stability and security purposes.
- 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.
Comments
Thanks...Its interesting, you provide such a wonderfull information, I'll try to do it.
heal!
function addi(a,b){
alert( a + b);
}
Very nice work, keep it up!
if it would be explained that how to arrange and how we can make a good search engine in html ........
what is function of result.php..............
and how it works
how it assign value of desire thing in path in web site
The table name in the query of search is wrong. It has to be $db_tb_name and not $tb_name. Otherwise it is fine.
Thank you so much.
I think this is a great article, but you need to add some security from SQL injections. I would suggest that this article change the first line to $query=mysql_real_escape_string($_GET['query']);
Also, this line should be moved to the line under the MySQL database connection (line 17) to avoid an error.
I appreciate this code, it's really very interesting to me because it turns my black day to yellow day.
My thanks go to hotwebideas who plays a great job on securing the code.
Warm regards!!
bakwas
@monika, I Also think so... But this article is for beginners...
If you want... I can write another tutorial on building advanced search engine while Using PHP as programming language.
My Qoute: "Nothing is impossible in programming - As long as you have interest and your concepts are clear - Basics are more important"
i get a blank page when i run the search script.
Hello @petermourra, Thanks for notification.... I Updated this script again... Try it Now... It is working on my computer.
Note: Create a separate Page (search.php) for PHP Script as per the instructions shown above (If you're a newbie) Otherwise, You know how to deal with forms.
why there are still have an error on line 22?
it give this command -->
Warning: mysql_fetch_array() expects parameter 1 to be resource, boolean given in C:\wamp\www\TELEKOM project\search_result.php on line 22
It is working on my Computer... (Executed Again)
Check points listed below:
1) Did You Started MySQL before running this script on your server.
2) Did You Created Database, Table and it's attribute inside MySQL on which search action is to be performed.
3) Did You Submitted correct values to this variables,
$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";
OR You May Did some erroneous changes in MySQL Query.
One More Point : Does Column Name of Table on Which search action is to be performed has some rows containing data or is Blank. If Blank, Then, You need not to worry about this type of errors.
Thanks for Notifying Me.
ok thanks. it's setel when i change my table name from "customer" to "customer info". it error when it have spacing.
thanks again.
correction.
*it is from "customer info" to "customer".
Great work very helpful,
I'm trying to alter this so it outputs a paginated list of photos with text one ofter another when you search, like some real estate sites list search results, can you help me understand the changes required?
hey everyone!
I want to create a search engine website like google/ask/yahoo... what should i do?? should i create my sql database? please help me...
Developing a searching engine like google/ask/yahoo is very hard task. The search engine we created here on this page is like a micro bacteria in respect to them. I would suggest not to waste your time in doing that because It requires lots of web space, time, good algorithms, multiple computers and Huge power of CPUs etc.
Well, If you want to start with small such as with single website or group of websites, then, you can do that by simply using MySQL and PHP. you just only need to manipulate and match strings.
hi can any one make a search with 2 textfiled like the indeed.co.uk
thanks
arning: mysql_fetch_array() expects parameter 1 to be resource, boolean given in C:\wamp\www\TELEKOM project\search.php on line 22
Check if column name of database table specified in MySQL query is not empty.
thanks............a........ .lot.........
You're welcome.
Thank u so much.......
I used this tutorial and it works perfectly.
But I need help.
Question: How do I attach the results found a url from the database because when give click on a result to be redictionat the website.
Thanks for help.
can u please tell me how to create database in microsoft acess. i am creating a search engine in java
Use contact form from my profile... I'll try my best to assist you.
Hey Itech, I commented on this hub 7 months ago and see that you changed the PHP code to mysql_real_escape_string() to prevent SQL injections. Thanks. Nice to know someone took my advice. LOL Still, this was a great article.
Thank you very much! This realy helped me! :) You are the best!
Has anyone created a PHP search engine using Drupal or Joomla?
Great Tutorial for begginer...
FindYourSearch 18 months ago
Thank you for this, very interesting and useful.