Home arrow PHP arrow Page 2 - Performing Full-text and Boolean Searches with MySQL

Running SELECT queries using a common approach - PHP

When a database-driven web site grows past a certain size, it requires an internal search engine. If it is a very big site, it may be desirable for visitors to be able to use full-text searches and Boolean operators to find the information they need. This article, the first of a three-part series, explains why and shows you how to work with full-text and Boolean searches using MySQL and PHP 5.

  1. Performing Full-text and Boolean Searches with MySQL
  2. Running SELECT queries using a common approach
  3. Using full-text searches with MySQL
  4. Building the Web Form
By: Alejandro Gervasio
Rating: starstarstarstarstar / 6
June 06, 2007

print this article



We can start learning about using full-text and Boolean searches with MySQL by developing a simple search engine. Our example will use the popular "LIKE" SQL statement to collect database information according to a specific search term entered by a fictional user.

Having said that, this basic MySQL-based search engine could be implemented through the definition of two simple files, whose signatures are listed below:

(definition of form.htm file)

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"

<html xmlns="http://www.w3.org/1999/xhtml">


<meta http-equiv="Content-Type" content="text/html; charset=iso-
8859-1" />

<title>Example of simple MySQL search engine</title>

<style type="text/css">


            padding: 0;

            margin: 0;

            background: #fff;



            font: bold 16px Arial, Helvetica, sans-serif;

            color: #000;

            text-align: center;



            font: bold 11px Tahoma, Arial, Helvetica, sans-serif;

            color: #000;



            width: 40%;

            padding: 10px;

            margin-left: auto;

            margin-right: auto;

            background: #6cf;





<h1>Example of simple MySQL search engine</h1>

<div id="formcontainer">

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

<p>Enter search term here : <input type="text" name="searchterm"
title="Enter search term here" /><input type="submit"
name="search" value="Search Now!" /></p>





(definition of search.php file)


// define 'MySQL' class

class MySQL{

private $conId;

            private $host;

            private $user;

            private $password;

            private $database;

            private $result;

            const OPTIONS=4;

            public function __construct($options=array()){


                                               throw new
Exception('Invalid number of connection parameters');


                        foreach($options as $parameter=>$value){


                                               throw new
Exception('Invalid parameter '.$parameter);






            // connect to MySQL

            private function connectDB(){


                                               throw new
Exception('Error connecting to the server');



                                               throw new
Exception('Error selecting database');



            // run query

            public function query($query){


                                               throw new
Exception('Error performing query '.$query);


                        return new Result($this,$this->result);


            public function escapeString($value){

return mysql_escape_string($value);



// define 'Result' class

class Result {

private $mysql;

            private $result;

            public function __construct(&$mysql,$result){




            // fetch row

            public function fetchRow(){

                        return mysql_fetch_assoc($this->result);


            // count rows

            public function countRows(){


                                               return false;


                        return $rows;


            // count affected rows

            public function countAffectedRows(){


                                               throw new Exception('Error counting affected rows');


                        return $rows;


            // get ID form last-inserted row

            public function getInsertID(){


                                               throw new
Exception('Error getting ID');


                        return $id;


            // seek row

            public function seekRow($row=0){


                                   throw new Exception('Invalid
result set offset');



                                   throw new Exception('Error
seeking data');





            // connect to MySQL

            $db=new MySQL(array


            $result=$db->query("SELECT * FROM articles WHERE
title LIKE '%$searchterm%' ORDER BY id ASC");


                        echo 'No results were found.';



                        echo '<h2>Articles returned are as


                                   echo '<p>Title: '.$row
['title'].' Author: '.$row['author'].' Description: '.$row




catch(Exception $e){

            echo $e->getMessage();




As you can see, the two files listed above implement a primitive MySQL-based search engine. The first file simply displays a web form for entering different search terms, and the second one performs the searching process against a sample "ARTICLES" database table.

As shown above, this task is carried out by two MySQL-processing classes, which may already be familiar to you -- I've been using them with some of my previous PHP articles published on the prestigious Developer Shed network.

However, the most important thing to notice here is the use of the traditional "LIKE" SQL statement inside the SELECT query. It allows us to retrieve the corresponding results from the database table according to a specified search term, as indicated below:

$result=$db->query("SELECT * FROM articles WHERE title LIKE '%
$searchterm%' ORDER BY id ASC");

We'll assume that the sample "ARTICLES" database table has been previously populated with the following basic records:

Id                  Title                         Author                                 Content

1  This is the title of article 1  Alejandro Gervasio      This is the content of article 1
2  This is the title of article 2  John Doe                     This is the content of article 2
3  This is the title of article 3  Mary Wilson                 This is the content of article 3

If the search string "article 1" were entered in the corresponding web form, the search engine would return the following query result:

Articles returned are as following:

Title: This is the title of article 1 Author: Alejandro Gervasio
Description: This is the content of article 1

You have probably used the "LIKE" statement hundreds of times before with your SELECT queries, so the previous example should be pretty easy to grasp. In this case, I built a basic but effective internal search engine that uses MySQL as its principal workhorse. That was quite simple to implement, right?

Nevertheless, as the databases that integrate the back end of a given web site or PHP application grow in size, the queries performed using the familiar "LIKE" command can introduce a considerable overhead in the server. This doesn't even consider what happens when the SELECT statements involve the utilization of multiple databases and tables! Yes, certainly this kind of query may take several seconds to run, and as I said before, can seriously compromise the performance of the web server.

Considering the aforementioned performance issue, here is where full-text searches come in. They can noticeably speed up the execution of large and complex queries, in this way improving the overall performance of the application in which they are used.

However, the details on how to use full-text searches with MySQL will be discussed in the following section, so click on the link below and keep reading.

>>> More PHP Articles          >>> More By Alejandro Gervasio

blog comments powered by Disqus
escort Bursa Bursa escort Antalya eskort


- Hackers Compromise PHP Sites to Launch Attac...
- Red Hat, Zend Form OpenShift PaaS Alliance
- PHP IDE News
- BCD, Zend Extend PHP Partnership
- PHP FAQ Highlight
- PHP Creator Didn't Set Out to Create a Langu...
- PHP Trends Revealed in Zend Study
- PHP: Best Methods for Running Scheduled Jobs
- PHP Array Functions: array_change_key_case
- PHP array_combine Function
- PHP array_chunk Function
- PHP Closures as View Helpers: Lazy-Loading F...
- Using PHP Closures as View Helpers
- PHP File and Operating System Program Execut...
- PHP: Effects of Wrapping Code in Class Const...

Developer Shed Affiliates


Dev Shed Tutorial Topics: