MySQL
  Home arrow MySQL arrow Page 2 - Completing a Search Engine with MySQL ...
Dev Shed Forums 
Administration  
AJAX  
Apache  
BrainDump  
DHTML  
Flash  
Java  
JavaScript  
Multimedia  
MySQL  
Oracle  
Perl  
PHP  
Practices  
Python  
Reviews  
Security  
Style-Sheets  
Web Services  
XML  
Zend  
Zope  
Forums Sitemap 
IBM® developerWorks 
Sun Developer Network 
Dedicated Servers 
E-Commerce Hosting 
Linux Web Hosting 
Managed Hosting 
Small Business Hosting 
Moblin 
JMSL Numerical Library 
VPS Hosting 
Weekly Newsletter

 
Developer Updates  
Free Website Content 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us Get Paid 
Request Media Kit
Contact Us 
Site Map 
Privacy Policy 
Support 
 USERNAME
 
 PASSWORD
 
 
  >>> SIGN UP!  
  Lost Password? 
MYSQL

Completing a Search Engine with MySQL and PHP 5
By: Alejandro Gervasio
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: 4 stars4 stars4 stars4 stars4 stars / 8
    2007-08-13

    Table of Contents:
  • Completing a Search Engine with MySQL and PHP 5
  • Listing the full source code of the original search application
  • Defining a simple web page generating class
  • Developing a fully-functional practical example

  • Rate this Article: Poor Best 
      ADD THIS ARTICLE TO:
      Del.ici.ous Digg
      Blink Simpy
      Google Spurl
      Y! MyWeb Furl
    Email Me Similar Content When Posted
    Add Developer Shed Article Feed To Your Site
    Email Article To Friend
    Print Version Of Article
    PDF Version Of Article
     
     
    ADVERTISEMENT


    Completing a Search Engine with MySQL and PHP 5 - Listing the full source code of the original search application


    (Page 2 of 4 )

    As usual with many of my articles on PHP web development, before I proceed to implement the session mechanism for maintaining the value of a given search string across different web pages, I'd like to list all of the source files that comprise this search application as they were originally defined in the previous article of the series.

    That being said, here are the signatures for the source files:

    (definition of "form.htm" file)

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=iso-
    8859-1" />
    <title>MySQL-based Search Engine</title>
    <link href="default.css" rel="stylesheet" type="text/css"
    media="screen" />
    <script language="javascript" type="text/javascript">
    window.onload=function(){
       if(document.getElementById && document.getElementsByTagName &&
    document.createElement){
         var sfield=document.getElementsByTagName('form')[0].elements
    [0];
         if(!sfield){return};
         sfield.onfocus=function(){this.value=''};
         sfield.onblur=function(){
           if(!this.value){this.value='Enter your search term here'};
         }
       }
    }
    </script>
    </head>
    <body>
     
    <h1>MySQL-based Search Engine</h1>
     
    <div class="maincontainer">
       
    <form method="get" action="processform.php">
         
    <input type="text" name="searchterm" title="Enter your
    search term here" value="Enter your search term here"
    class="searchbox" />
         
    <input type="submit" name="search" title="Search Now!
    "value="Search" class="searchbutton" />
       
    </form>
     
    </div>
    </body>
    </html>

    (definition of "default.css" file)

    body{
       background: #ccc;
       margin: 0;
       padding: 0;
    }

    h1{
       width: 375px;
       padding: 10px;
       margin-left: auto;
       margin-right: auto;
       background: #339;
       font: normal 18px Arial, Helvetica, sans-serif;
       color: #fff;
       border: 1px solid #000;
       text-align: center;
    }

    h2{
       font: bold 18px  Arial, Helvetica, sans-serif;
       color: #339;
    }

    p{
       font: normal 10pt Arial, Helvetica, sans-serif;
       color: #000;
    }

    a:link,a:visited{
       font: normal 10pt Arial, Helvetica, sans-serif;
       color: #00f;
       text-decoration: none;
    }

    a:hover{
       color: #f00;
       text-decoration: underline;
    }

    .maincontainer{
       width: 375px;    
       padding: 10px;
       margin-left: auto;
       margin-right: auto;
       background: #f0f0f0;
       border: 1px solid #000;
    }

    .rowcontainer{
       padding: 10px;
       margin-bottom: 10px;
       background: #ccf;
    }

    .searchbox{
       width: 200px;
       font: normal 12px Arial, Helvetica, sans-serif;
       color: #000;
    }

    .searchbutton{
       width: 80px;
       font: bold 12px Arial, Helvetica, sans-serif;
       color: #000;      
    }

    (definition of "mysql.php" file)

    <?php
    // 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()){
         if(count($options)!=self::OPTIONS){
           throw new Exception('Invalid number of connection
    parameters');
         }
         foreach($options as $parameter=>$value){
           if(!$value){
             throw new Exception('Invalid parameter '.$parameter);
           }
           $this->{$parameter}=$value;
         }
         $this->connectDB();
       }
       // connect to MySQL
       private function connectDB(){
         if(!$this->conId=mysql_connect($this->host,$this-
    >user,$this->password)){
           throw new Exception('Error connecting to the server');
         }
         if(!mysql_select_db($this->database,$this->conId)){
           throw new Exception('Error selecting database');
         }
       }
       // run query
       public function query($query){
         if(!$this->result=mysql_query($query,$this->conId)){
           throw new Exception('Error performing query '.$query);
         }
         return new Result($this,$this->result,$query);
       }
       public function escapeString($value){
         return mysql_escape_string($value);
       }
    }
    // define 'Result' class
    class Result {
       private $mysql;
       private $result;
       private $query;
       private $rowTemplate='default.tpl';
       private $numRecs=4;
       public function __construct($mysql,$result,$query){
         $this->mysql=$mysql;
         $this->result=$result;
         $this->query=$query;
       }
       // fetch row
       public function fetchRow(){
         return mysql_fetch_assoc($this->result);
       }
       // count rows
       public function countRows(){
         if(!$rows=mysql_num_rows($this->result)){
           return false;
         }
         return $rows;
       }
       // count affected rows
       public function countAffectedRows(){
         if(!$rows=mysql_affected_rows($this->mysql->conId)){
           throw new Exception('Error counting affected rows');
         }
         return $rows;
       }
       // get ID form last-inserted row
       public function getInsertID(){
         if(!$id=mysql_insert_id($this->mysql->conId)){
           throw new Exception('Error getting ID');
         }
         return $id;
       }
       // seek row
       public function seekRow($row=0){
         if(!is_int($row)||$row<0){
           throw new Exception('Invalid result set offset');
         }
         if(!mysql_data_seek($this->result,$row)){
           throw new Exception('Error seeking data');
         }
       }
       public function countFields(){
         if(!$fields=mysql_num_fields($this->result)){
           throw new Exception('Error counting fields.');
         }
         return $fields;
       }
      
    public function fetchPagedRows($page){
         $numPages=ceil($this->countRows()/$this->numRecs);
         if(empty($page)||$page>$numPages){
           $page=1;
         }
         $result=$this->mysql->query($this->query.' LIMIT '.($page-1)
    *$this->numRecs.','.$this->numRecs);
         $output='';
         while($row=$result->fetchRow()){
           $rowTemplate=file_get_contents($this->rowTemplate);
           foreach($row as $key=>$value){
             $rowTemplate=str_replace('{'.$key.'}',$value,$rowTemplate);
           }
           $output.=$rowTemplate;
         }
         $output.='<p>';
         if($page>1){
           $output.='<a href="'.$_SERVER['PHP_SELF'].'?&page='.
    ($page-1).'">&lt;&lt;</a>&nbsp;';
         }
         for($i=1;$i<=$numPages;$i++){
           $output.=$i!=$page?'<a href="'.$_SERVER['PHP_SELF'].'?
    page='.$i.'">'.$i.'</a>&nbsp;':$i.'&nbsp;';
         }
         if($page<$numPages){
           $output.='&nbsp;<a href="'.$_SERVER['PHP_SELF'].'?&page='.
    ($page+1).'">&gt;&gt;</a>';
         }
         $output.='</p>';
         return $output;
       }
    }
    ?>

    (definition of 'default.tpl' file)

    <div class="rowcontainer">
     
    <p><strong>First Name:</strong> {firstname}</p>
     
    <p><strong>Last Name:</strong> {lastname}</p>
     
    <p><strong>Comments:</strong> {comments}</p>
    </div>

    (definition of "sessionhandler.php" file)

    <?php
    class SessionHandler{
       public function __construct(){
         session_start();
       }
       public function setVariable($value='default',$varname='default'){
         $_SESSION[$varname]=$value;
       }
       public function getVariable($varname='default'){
         if(!$_SESSION[$varname]){
           return false;
         }
         return $_SESSION[$varname];
       }
       public function destroy(){
         session_start();
         session_unset();
         session_destroy();
       }
    }
    ?>

    As you can see, all the above source files perform well-differentiated tasks, in this way implementing the distinct application modules that comprise the search engine. These range from displaying a simple web form for entering diverse search terms to executing the search queries against one or more MySQL databases.

    Besides, you should notice that I defined a template file called "default.tpl" which is used by the previous "Result" PHP class to format the results returned by a query. This record formatting process can be done directly from inside the class.

    So far, so good right? At this stage I have shown you the complete signatures corresponding to all the source files that make up this MySQL-based search engine. So what is the next step?

    Well, considering that all the database results returned by a specific query must be displayed on a separate web page, in the following section I'm going to define yet another PHP class. It will be tasked with building basic web documents, which makes it quite useful in conjunction with the rest of the source files that you saw earlier.

    Want to see how this brand new PHP class will be built? Jump ahead and read the next few lines.   

    More MySQL Articles
    More By Alejandro Gervasio


       · Over the course of this final tutorial of the series, this MySQL/PHP 5 - based...
       · It's a decent simple search engine, but that's all really. It gets tougher when you...
       · Thank you for commenting on my PHP article. You’re correct regarding the simplicity...
       · Getting a grasp on classes in php is difficult for some, like myself, but your...
       · Thank you for the kind comments on my PHP article, and it's always good to know it's...
       · Hi, Thanks for the detailed tutorial. I began with confidence but I have...
       · Thank you for the comments on my PHP article. Now, concerning your question, the...
       · Hi Alejandro,Thank you for taking your time to reply. I read your entire...
       · Hi JSP,Thanks again for posting here. Now that you've created a "processform.php"...
       · Thanks Alejandro,That helps... WOW I wouldn't have guessed that, since I am no...
       · Hi JSP,Glad to know the search engine is working for you. Thanks again for the...
     

       

    MYSQL ARTICLES

    - Take Some Load off MySQL with MemCached
    - MySQL Table Prefix Changer Tool in PHP
    - Using the SIGNAL Statement for Error Handling
    - Error Handling Examples
    - Error Handling
    - Completing a Search Engine with MySQL and PH...
    - Paginating Result Sets for a Search Engine B...
    - Building a Search Engine with MySQL and PHP 5
    - Using Boolean Operators for Full Text and Bo...
    - PHP, MySQL and the PEAR Database
    - Working with PHP and MySQL
    - Getting PHP to Talk to MySQL
    - Creating an RSS Reader: the Reader
    - MySQL Security Overview
    - Creating the Admin Script for a PHP/MySQL Bl...





    © 2003-2008 by Developer Shed. All rights reserved. DS Cluster 1 hosted by Hostway