Creating A Simple Search Engine In PHP

search-engine-optimization-blogThis is the first in what I hope will be a long list of tutorials that I like to call Practical Programming in PHP. Lets get down to business, today I’m going to show you how to create a simple search engine that you can use for your very own site or some other project that you may be working on. For this tutorial I will be using a MySQL database. The bulk of the code should be compatible with PHP 3 and 4.

Background:

Before we begin, I’ll show you the table I’ll be using in the examples:

First_NameMiddle_NameLast_Name
DanaJohnsonSmith
JillAngelPetersburg
JackConerMitchel

If you feel confused about any of the functions in the tutorial, have a look at my previous tutorial that deals with common database functions.

Down To Work:

Before we actually make the search engine, we need to create a basic webpage that will have an input field where the user can enter his or her search query. I’m going to keep mine simple; feel free to make an elaborate one with lots of bells and whistles. The code for my page is below:

[php]<html>

<head>

  <title>Simple Search Engine version 1.0</title>

</head>

<body>

  <center>

    Enter the first, last, or middle name of the person you are looking for:

    <form action="search.php" method="post">

      <input type="text" name="search_query" maxlength="25" size="15"><br>

      <input type="reset" name="reset" value="Reset"> 

      <input type="text" name="submit" value="Submit">

    </form>

  </center> 

</body>

</html>[/php]

It’s a pretty basic page so I’m not going to explain alot of it. Basically, the user will enter the first, middle, or last name of the person they are looking for and hit enter. The contents of the input field will be passed to a php script named “search.php” which will handle the rest.

Now that the page is out of the way, let’s create the actual script. First, we need to connect to the database using mysql_pconnect() and select the table using mysql_select_db(). Next, we want to parse the value passed to the script to see if it contains any invalid input, such as numbers and funky characters like #&*^. You should always validate input, don’t rely on things like JavaScript to do it for you, because once the user disables JavaScript all that fancy validation goes down the toilet. To check the input we are going to use a regular expression, they are a bit confusing and will be explained in a later tutorial. For now, all you need to know is that it will check to see if value passed is a string of characters. All right, enough chatter, here is the first part of the script:

[php]<?php 

  mysql_pconnect("host", "username", "password") or die("Can't connect!");

  mysql_select_db("Names") or die("Can't select database!"); 

  if (!eregi("[[:alpha:]]", $search_query))

  {

    echo "Error: you have entered an invalid query, you can only use characters!<br>";

    exit;

  }
[/php]

Now that we’ve done that, we will form the search query.

[php]$query= mysql_query("SELECT * FROM some_table WHERE First_Name= '$search_query' 

OR Middle_Name= '$search_query' OR Last_Name= '$search_query' ORDER BY Last_Name");[/php]

Look confusing? I’ll explain, what’s happening is, we’re asking MySQL to search all the rows in First_Name, Middle_Name, and Last_Name for a match to the query entered by the user; then, take the results of that search, alphabetize the results by Last_Name.

The rest of the coding from now on is a breeze. We will get the results from the query using mysql_fetch_array( ), and check to see if there is a match using mysql_num_rows(). If there is a match, or matches, we will output it along with the number of matches found; if there isn’t, we’ll report to the user that we couldn’t find anything.

 [php]$result= mysql_num_rows($query);

  if ($result == 0)

  {

    echo "Sorry, I couldn't find any user that matches your query ($search_query)";

    exit; 

  }

  else if ($result == 1)

  {

    echo "I've found <b>1</b> match!<br>";

  }

  else {

    echo "I've found <b>$result</b> matches! <br>";

  }

  while ($row= mysql_fetch_array($query))

  {

    $first_name= $row["First_Name"];

    $middle_name = $row["Middle_Name"];

    $last_name = $row["Last_Name"];

    echo "The first name of the user is: $first_name.<br>";

    echo "The middle name of the user is: $middle_name.<br>";

    echo "The last name of the user is: $last_name.<br>";

  }

?>[/php]

I added that extra if statement so that when we report how many users we’ve found, its output will be in proper English. If I we don’t, the script will echo “I’ve found 1 matches” which obviously isn’t good grammar 😛 The rest of the script loops through the results and prints them to a webpage. That’s all, we’ve finished the script! The entire script is included below:

[php]<html>

<head>

  <title>Simple Search Engine version 1.0 - Results </title>

</head>

<body> 

<?php 

  mysql_pconnect("host", "username", "password") or die("Can't connect!");

  mysql_select_db("Names") or die("Can't select database!"); 

  if (!eregi("[[:alpha:]]", $search_query))

  {

    echo "Error: you have entered an invalid query, you can only use characters!<br>";

    exit; //No need to execute the rest of the script.

  }

  $query= mysql_query("SELECT * FROM some_table WHERE First_Name='$search_query' 

  OR Middle_Name= '$search_query' OR Last_Name='$search_query' ORDER BY Last_Name");

  $result= mysql_numrows($query);

  if ($result == 0)

  {

    echo "Sorry, I couldn't find any user that matches your query ($search_query)";

    exit; //No results found, why bother executing the rest of the script?

  }

  else if ($result == 1)

  {

    echo "I've found <b>1</b> match!<br>";

  }

  else {

    echo "I've found <b>$result</b> matches!<br>";

  }

  while ($row= mysql_fetch_array($query))

  {

    $first_name= $row["First_Name"];

    $middle_name = $row["Middle_Name"];

    $last_name = $row["Last_Name"];

    echo "The first name of the user is: $first_name.<br>";

    echo "The middle name of the user is: $middle_name.<br>";

    echo "The last name of the user is: $last_name. <br>";

  }

?> 

</body>

</html>[/php]

Facebook Comments

5 Responses to “Creating A Simple Search Engine In PHP”

  1. studentur says:

    пока я жив, я буду помнить ваш ресурс 🙂 заношу в букмарки….

  2. NFS gamer says:

    Очень рада, что возникло желание взять этот пост в цитатник!

  3. Odmin says:

    Понравилась статья. Обязательно буду ждать продолжения. Эта тема конечно же интересна всем.

Leave a Reply


Related Posts