How to Create a Search Engine for Your Site

18 Jan

In this post, you will learn how to build your own search function, allowing your visitors to search through your site using an HTML search form. We are using PHP and MySQL languages. I will hopefully provide you with the most basic and straightforward code available, and feel free to copy and paste this into your own code.

Let’s get started! Here is the first HTML snippet to create a search button and form to accept user input:


<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 within the body tag and customize it’s look via CSS (See http://www.webdesignerer.wordpress.com/Modern-CSS3-Search-Form/). Now, here is the PHP snippet that will retrieve results from our MySQL database. Save this code on another page with the filename search.php.

<?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 search

// 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_nameWHERE

 

$db_tb_atr_namelike '%".$query."%'");

echo"<h2>Search Results</h2><ol>";

while($data_fetch=mysql_fetch_array($query_for_result))

{

    echo"<li>";

    echosubstr($data_fetch[$db_tb_atr_name], 0,160);

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

}

echo"</ol>";

 

mysql_close();

?>

You have just created your first search engine! If you found this information useful or if you found any errors in the code, please leave a comment! Also be sure to check out our new facebook page at https://www.facebook.com/pages/The-webdesignerer-Blog/322090944479607!

About these ads

2 Responses to “How to Create a Search Engine for Your Site”

  1. ouija board February 4, 2012 at 4:24 pm #

    i love your blog, i have it in my rss reader and always like new things coming up from it.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

Join 368 other followers

%d bloggers like this: