A Quick Snippet Of Help
 

Back | Print Version

Web Development (Coding)

Oyster Web Articles

DIY Search Engine With PHP

A Quick Snippet Of Help


by Rupert Sharp
of http://www.oyster-web.co.uk

Last updated: 11 Dec 2007

Ever wanted to have your very own search engine? Ever wanted to find a record in your database quickly? Well now you can! Etc.
Below I have written a PHP code for making a pretty basic search engine that will look through user records to find the username(s) similar to your search, I recently had to code one of these and thought it would be a useful little thing to show you all. The code obviously needs personalised for it to work but its standard enough for it to be portable, you can add all your own search parameters to it to make it do what you want it to do.

Above HTML Tag:

<?php
if($_GET['search'] == "yes" && $_GET['name'] != NULL)
{
//this would be the document containing your connection code for your database
require_once('connecting.php');
//now selecting database
mysql_select_db($database_jimbob, $connect);
//this selects the username and age from the table where the username is similair to the information the user has submitted, it then orders the results randomly and limits the number of records to 30
$query_Rset1 = "SELECT username, age FROM users WHERE username LIKE '%$_GET[name]%' ORDER BY RAND() LIMIT 30";
$Rset1 = mysql_query($query_Rset1, $connect) or die(mysql_error());
//counts the rows returned
$totalRows_Rset1 = mysql_num_rows($Rset1);
}
?>

The body code:



<?php
//if the search has not been submitted write the form
if($_GET['search'] == NULL)
{
echo('Hello are you looking for a user?<br /><form action="'.$PHP_SELF.'" method="GET">Username:<input type="text" name="name" size="12" maxlength="12" /><input type="submit" />');
}else{echo('Your search - "'.$_GET['name'].'" returned:<hr />');}
//now the results, if records matching criterea have been found write username and age
if ($totalRows_Rset1 != 0){
while ( $row = mysql_fetch_array($Rset1) )
{
echo (htmlspecialchars($row[username]) .' '. htmlspecialchars($row[age]) . '<br />);
}}
//if a search has been made but no records returned tell user
elseif($_GET['search'] == 'yes' && $totalRows_Rset1 == 0)
{echo ('Sorry no users matched your search'); }
//if no search has been made
else{ echo('Please make a search query');}
?>

I hope this proves useful in some way or form. : - D

Search Engine Optimization