Coding the Search Box

Written by: burt
Date: January 14, 2010
Filed under: Project 2010
Trackback · Comment

On the site I want to cut down on customer contact (eg, emailing to ask if XYZ surname is available) – so I definitely want some sort of search box.

I have all the surnames in a txt file (I think there are about 50,000 surnames). So it's pretty large. A while back I worked on a site with something very similar though this was for searching "town names".

The PHP code goes like this;

function haveSurname($surname) {
$got = false;
$fp = fopen('file.txt', 'rb');
while ($line = trim(fgets($fp))) {
if (strtolower($line) == strtolower(stripslashes($surname))) {
$got = true;
break;
}
}
fclose($fp);
return $got;
}

As you can probably tell, this searches thru a file and returns "true" (1) or "false" (0) depending upon whether the term searched for exists! Linking the above code to a simple input in a form;

< input id="search" type="text" name="surname" / >

and then echoing the result;

echo (haveSurname($_POST['surname']) == 1) ? "Found " . $_POST['surname'] : "Sorry, " . $_POST['surname'] . "not found.";

Will tell the person searching if their name exists in the database or not. Of course, if the surname doesn't exist I could offer a service where I spend time investigating their surname (obviously for suitable expenses), but I don't want to offer that right now as I want this site to consume as little of my time as is possible.

Leave a comment



Did you enjoy reading this?
Please consider subscribing to our RSS Feed!


Subscribe by Email
Get notified by email every time we update this Blog!


 

Subscribe (RSS)

Recent Comments

Sponsored By

What Others Are Saying