Publishers of technology books, eBooks, and videos for creative people

Home > Articles > Web Design & Development > PHP/MySQL/Scripting

  • Print
  • + Share This
From the author of

Performing a Search

With the site’s content indexed, it’s time to create the search engine itself. The search form just needs a text input, which I’d call terms. The form would be submitted to search.php. Normally search forms are submitted via GET.

The search page must first verify that something was provided in $_GET['terms']. Then the page should apply strtolower(), strip_tags(), and an escaping function to make the terms safe to use in a query:

$terms = mysqli_real_escape_string($dbc, strip_tags(strtolower($_GET['terms'])));

Next, the terms must be broken into multiple words:

$terms = explode(' ', $terms);

Now the search query can be built up dynamically:

$q = 'SELECT p.page_url, SUM(pw.frequency) AS relevance FROM se_pages AS p INNER JOIN se_pages_words AS pw USING (page_id) INNER JOIN se_words AS w USING (word_id) WHERE';
foreach ($terms as $term) {
    $q .= " word='$term' OR";
}
$q = substr($q, 0, -3);
$q .= ' GROUP BY pw.page_id ORDER BY relevance DESC';

After building up the query, execute it and fetch the results (see the search.php script for details). For this particular example, the end result (Figure 2) isn’t fancy, but the search engine works, which is the most important thing. It shouldn’t be too hard for you to add some flair to this structure. Naturally, you’d want to paginate the query results, too.

Figure 2

Figure 2 The simple output for the search results.

  • + Share This
  • 🔖 Save To Your Account