Syndicate content
> PHP Search Engine Script Tutorial : Page One

PHP Search Engine Script Tutorial : Page One

Page One
Page Two


Page One

As is usually the case, this tutorial has come about as a result of a project that I got myself tangled up in...

Here's the scoop: Joy in the Harvest has a mammoth newsletter archive that didn't have any search capabilities, so I needed an easy way of doing a topical search.

Now, I should prelude this by saying that there are about two trillion ways of designing and implementing a search engine, but this is a quick easy one (in fact, you can basically copy/paste the source code if you don't feel like reading the tutorial).

What I was aiming for was to keep everything on one page for the sake of ease for the user. Okay, let's take a look at the first piece of code:


$var = @$_GET['q'] ; // get the query for the search engine (if applicable)
$trimmed = trim($var); //trim whitespace from the stored variable

This PHP code snippet should go in above the <head> of the document. The first line retrieves the "q" ("q" stands for query, in case you were wondering) from the search. The second line strips any white spaces.

Next we're going to need to connect to the database...


$user = "username"; // AN EDIT IS REQUIRED HERE
$password = "password";
$host = "host";
$dbase = "dbase";
$table = "table";

// Connection to DBase
mysql_connect($host,$user,$pass);
@mysql_select_db($dbase) or die("Unable to select database");

The above variables need to be set (obviously) to whatever is applicable to your host/database.

Okay, now we're going to talk about the database structure a little bit. Basically, what I've done is added a field to the dbase called "keywords". Then, I entered comma-separated values that I wanted to associate with that particular letter. Take a look at the code:


$field_to_search = "field";
$query = "SELECT * FROM $table WHERE $field_to_search LIKE \"%$trimmed%\" order by id";

$result = mysql_query($query);
$count =mysql_numrows($result);

So, these four lines do this:

1) Set the field to search as a variable called $field_to_search
2) Query the database for the searched term
3) Return the results
4) Count the results (for aesthetic purposes later)

Up to this point, all of this PHP code should be in or above the <head> section. To be 100% honest, it doesn't really matter if it is or isn't in the <head> section, but I like to keep my "backend" PHP up there because it's "out of the way" (so to speak).

On the next page, we'll cover returning the results -- the code for the <body> tags.


Luke Wertz
www.iLuke.netLuke Wertz is an 18-year-old missionary kid serving in Kigoma, Tanzania (East Africa). In his spare time, he enjoys playing his guitar with a worship team, working with computers and digital photography. You can visit him online at www.joyintheharvest.com .

User login

Christian-Web-Masters.com newsletter

Stay informed on our latest news!