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

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.

More by this Author


Comments 57 comments

FindYourSearch profile image

FindYourSearch 5 years ago from Las Vegas, NV

Thank you for this, very interesting and useful.


temp_inizer profile image

temp_inizer 5 years ago from Noida (India)

Thanks...Its interesting, you provide such a wonderfull information, I'll try to do it.


awe 5 years ago

heal!

function addi(a,b){

alert( a + b);

}


themastudios profile image

themastudios 5 years ago from Melbourne, FL

Very nice work, keep it up!


ram 5 years ago

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


Ishraga M Allam 5 years ago

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.


hotwebideas profile image

hotwebideas 5 years ago from New York

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.


NTWALI Jean Paul 5 years ago

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!!


monika 5 years ago

bakwas


itech profile image

itech 5 years ago from New Delhi, India Author

@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"


petermourra 5 years ago

i get a blank page when i run the search script.


itech profile image

itech 5 years ago from New Delhi, India Author

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.


najwa 5 years ago

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


itech profile image

itech 5 years ago from New Delhi, India Author

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.


itech profile image

itech 5 years ago from New Delhi, India Author

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.


najwa 5 years ago

ok thanks. it's setel when i change my table name from "customer" to "customer info". it error when it have spacing.

thanks again.


najwa 5 years ago

correction.

*it is from "customer info" to "customer".


coolaust 4 years ago

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?


Xafyr 4 years ago

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


itech profile image

itech 4 years ago from New Delhi, India Author

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.


danny 4 years ago

hi can any one make a search with 2 textfiled like the indeed.co.uk

thanks


rajiv 4 years ago

arning: mysql_fetch_array() expects parameter 1 to be resource, boolean given in C:\wamp\www\TELEKOM project\search.php on line 22


itech profile image

itech 4 years ago from New Delhi, India Author

Check if column name of database table specified in MySQL query is not empty.


jasmeen 4 years ago

thanks............a........ .lot.........


itech profile image

itech 4 years ago from New Delhi, India Author

You're welcome.


Logesh 4 years ago

Thank u so much.......


ddsoftware 4 years ago

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.


Priya 4 years ago

can u please tell me how to create database in microsoft acess. i am creating a search engine in java


itech profile image

itech 4 years ago from New Delhi, India Author

Use contact form from my profile... I'll try my best to assist you.


hotwebideas profile image

hotwebideas 4 years ago from New York

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.


Marian 4 years ago

Thank you very much! This realy helped me! :) You are the best!


hotwebideas profile image

hotwebideas 4 years ago from New York

Has anyone created a PHP search engine using Drupal or Joomla?


Zquery 4 years ago

Great Tutorial for begginer...


jake 4 years ago

thank you very much for this code, i was able to apply it to my small database that i created for my company. i really like it. thank you thank you


rain 4 years ago

it works ...thanks


Joe 4 years ago

Amazing. Thank you!!


Collins 4 years ago

I keep getting this error Warning: mysql_fetch_array(): supplied argument is not a valid MySQL result resource in /homepages/27/d394293414/htdocs/search.php on line 22

Line 22 ... while($data_fetch=mysql_fetch_array($query_for_result))

Please Help!


itech profile image

itech 4 years ago from New Delhi, India Author

Hello @Collis, Your database is empty.


Collins 4 years ago

hey @itech my databse isn't empty i put data in it to test it, i just put this in my code to test it ... if ( ! $query_for_result ) {

die ( mysql_error() ); // terminate script and output error

} and i got this error Table 'db394335150.Question' doesn't exist but im not sure where im supposed to insert the change at, i followed this pages php to the T


itech profile image

itech 4 years ago from New Delhi, India Author

@Collins, This error indicates that there is no such table exist in your database whose name is Question.

Check!

1) if database name is correct,

2) if table named as "Question" exist in your database on which you're performing your search.

Try performing search on another table of your database and check if response remains the same.


Collins 4 years ago

i figured out the problem, the table needed extra information. but now im getting this : Warning: mysql_fetch_array(): supplied argument is not a valid MySQL result resource in /homepages/27/d394293414/htdocs/itservices.php on line 164

Line 164 : while($data_fetch=mysql_fetch_array($query_for_result))


Collins 4 years ago

What is supposed to be put in the while loop to display the results?

// leave the below fields as it is except while loop, which will display results on screen


TDP 4 years ago

How would you hyperlink the results?


itech profile image

itech 4 years ago from New Delhi, India Author

Like this....

while($data_fetch=mysql_fetch_array($query_for_result))

{

echo "<li>";

echo '<a href="http://google.com">' . substr($data_fetch[$db_tb_atr_name], 0,160) . '</a>';

echo "</li><hr/>";

}


TDP 4 years ago

getting this error Warning: mysql_fetch_array(): supplied argument is not a valid MySQL result resource in(my information)


miniaudios 4 years ago

Friends, I as well need some help.

The response gives error as :

Warning: mysql_fetch_array(): supplied argument is not a valid MySQL result resource in /home/miniaudi/public_html/searchvideo/searchvideo.php on line 21

My DB is not empty..is there any specific I need to check


miniaudios 4 years ago

It's a really great and helpful article..

Thanks mate.


ucando262 4 years ago

This is great and easy to get working, however it is only 1/2 the battle. How can I extract a record number from the found results so I can update that particular record? The "A href" example above would be a great help if I could reference a found record for the user to edit... Now as it, it pulls all the records, but the user can't do anything with one of them... Could you provide one example of that? Thanks...


Alex 3 years ago

Thank you very much for this tutorial, it was so useful ..


Ryan Husband profile image

Ryan Husband 3 years ago

how can i get the data stored in $db_tb_atr_name to be used in hyperlink


Ryan Husband profile image

Ryan Husband 3 years ago

how can i get this to use the outputted data as the url example www.example.com/$db_tb_atr_name


s.pandey 3 years ago

nice one


Jammer 3 years ago

can i put a link on the result? that can view their files.


ronald 3 years ago

Thanks!


Prox 19 months ago

Warning: mysql_fetch_array() expects parameter 1 to be resource, boolean given in /Applications/XAMPP/xamppfiles/htdocs/xampp/Searchengine.php on line 32


itech profile image

itech 19 months ago from New Delhi, India Author

Hi Prox,

Did you created a table in db, with your preferred column name and have data there before executing search query?

Regards,

Krishna


no idea 9 months ago

Hello,

I am confused on how to use or create a pHp database.

Can you please explain more about this?:

$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";

Can you show me some examples?

Thanx

    Sign in or sign up and post using a HubPages Network account.

    0 of 8192 characters used
    Post Comment

    No HTML is allowed in comments, but URLs will be hyperlinked. Comments are not for promoting your articles or other sites.


    Click to Rate This Article
    working