PHP4-Compatible Object-Oriented Class for MySQL

If you find this code useful and would like to encourage me to post more goodies here, you could buy me something from my wish lists at Amazon.com or at MusicDirect.com

The following is a class I developed some time ago as part of my self-education in object-oriented programming. It is designed to be usable with PHP4 or later.


<?php
/**
*  class Mysql - PHP4/5-compatible OOP MySQL wrapper
*  created 2007/04/14 by Charles Reace (www.charles-reace.com)
*  This is freeware with no strings attached and absolutely NO warranty
*
*  Uses a config file which specifies the DB connection/selection parameters.
*  You can override the default config file pathname by specifying another
*  file as a parameter to the object instantiation, e.g.:
*     $db = new Mysql('/path/to/config/file.ini');
*
*  The file must set the following values:
*     dbHost = charles-reace.ipowermysql.com
*     dbUser = username
*     dbPwd  = password
*     database = database_name
*/
class Mysql
{
   var 
$iniFile 'xxx';  // ini file with db connection data
   // do not modify below this line unless you have a really good reason
   
var $dbHost '';
   var 
$dbUser '';
   var 
$dbPwd '';
   var 
$database '';
   var 
$connx NULL;
   var 
$error '';
   
   
/**
   *  void Mysql([str $iniFile])
   *  Purpose: constructor
   */
   
function Mysql($iniFile NULL)
   {
      if(!empty(
$iniFile))
      {
         
$this->iniFile $iniFile;
      }
      
$ini = @parse_ini_file($this->iniFile);
      if(
$ini == FALSE)
      {
         
user_error("Unable to read Mysql.ini"E_USER_WARNING);
      }
      else
      {
         
$attrs get_class_vars(__CLASS__);
         foreach(
$ini as $key => $val)
         {
            if(
array_key_exists($key$attrs))
            {
               
$this->$key $val;
            }
         }
      }
   }  
// end constructor
   
   /**
   *  bool connect()
   *  Purpose: connect to MySQL and select database
   */
   
function connect()
   {
      
$connx = @mysql_connect($this->dbHost$this->dbUser$this->dbPwd);
      if(
$connx != FALSE)
      {
         
$this->connx $connx;
         
$db mysql_select_db($this->database$this->connx);
         if(
$db == FALSE)
         {
            
$this->error "Unable to select DB: " mysql_error();
            
user_error($this->errorE_USER_WARNING);
            return(
FALSE);
         }
         return(
TRUE);
      }
      
$this->error "Unable to connect to DBMS: " mysql_error();
      
user_error($this->errorE_USER_WARNING);
      return(
FALSE);
   }  
// end connect()
   
   /**
   *  str sanitize(str $input)
   *  Purpose: sanitize input for use in SQL
   */
   
function sanitize($input)
   {
      
$input trim($input);
      if(!
is_numeric($input))
      {
         if(
get_magic_quotes_gpc())
         {
            
$input stripslashes($input);
         }
         
$input sprintf("'%s'", ($this->connx) ?
                          
mysql_real_escape_string($input) :
                          
mysql_escape_string($input));
      }
      return(
$input);
   }
   
   
/**
   *  mixed select(str sql)
   *  Purpose: execute SELECT query (or any query that returns result rows)
   *  returns QueryResult object on success, 0 if now rows, or FALSE on error
   */
   
function select($sql)
   {
      if(!
$this->connx)
      {
         
$this->error "Cannot process query, no DB connection.";
         
user_error($this->errorE_USER_WARNING);
         return(
FALSE);
      }
      
$result mysql_query($sql$this->connx);
      if(
$result)
      {
         if(
mysql_num_rows($result))
         {
            return(new 
QueryResult($result$this->connx));
         }
         else
         {
            return(
0);
         }
      }
      else
      {
         
$this->error "Query failed ($sql): " mysql_error();
         
user_error($this->errorE_USER_WARNING);
         return(
FALSE);
      }
   }  
// end select()
   
   /**
   *  int change(str $sql)
   *  Purpose: execute query that does not return result rows (e.g.: INSERT)
   *  Returns number affected rows, or FALSE on failure
   */
   
function modify($sql)
   {
      if(!
$this->connx)
      {
         
$this->error "Cannot process query, no DB connection.";
         
user_error($this->errorE_USER_WARNING);
         return(
FALSE);
      }
      
$result mysql_query($sql$this->connx);
      if(
$result)
      {
         return(
mysql_affected_rows($this->connx));
      }
      else
      {
         
$this->error "Query failed ($sql): " mysql_error();
         
user_error($this->error);
         return(
FALSE);
      }
   }  
// end modify()
   
   /**
   *  bool close()
   *  Purpose: close this MySQL connection
   */
   
function close()
   {
      return(
mysql_close($this->connx));
   }  
// end close()
   
}  // end class Mysql


/**
*  class QueryResult - result set and related functions from MySQL query
*  created 2007/04/14 by Charles Reace (www.charles-reace.com)
*  This is freeware with no strings attached and absolutely NO warranty
*/
class QueryResult
{
   var 
$result NULL;
   var 
$connx NULL;
   var 
$numRows 0;
   
   
/**
   *  void QueryResult(resource $result, resource $connx)
   *  Purpose: constructor
   */
   
function QueryResult($result$connx)
   {
      
$this->result $result;
      
$this->connx $connx;
      
$this->numRows mysql_num_rows($result);
   }  
// end constructor
   
   
function getRow($row NULL)
   {
      if(
$row !== NULL and is_numeric($row))
      {
         
mysql_data_seek($this->result, (int) abs($row));
      }
      return(
mysql_fetch_assoc($this->result));
   }  
// end getRow()
   
   /**
   *  str getTabel([bool $headers[, arr $labels]])
   *  Purpose: get query results as HTML table
   *  if $headers evaluates a TRUE, a header row will be included
   *  if $headers is TRUE and the $labels is an array, the values in $labels
   *     will be used as the column heading labels
   */
   
function getTable($headers FALSE$labels NULL)
   {
      
mysql_data_seek($this->result0);
      
$table "<table class='dbresult'>\n";
      if(
$headers)
      {
         
$table .= "<tr>";
         if(
is_array($labels))
         {
            foreach(
$labels as $label)
            {
               
$table .= "<th>$label</th>";
            }
         }
         else
         {
            
$num mysql_num_fields($this->result);
            for(
$ix 0$ix $num$ix++)
            {
               
$table .= "<th>".mysql_field_name($this->result,$ix)."</th>";
            }
         }
         
$table .= "</tr>\n";
      }
      while(
$row mysql_fetch_row($this->result))
      {
         
$table .= "<tr>";
         foreach(
$row as $val)
         {
            
$table .= "<td>$val</td>";
         }
         
$table .= "</tr>\n";
      }
      
$table .= "</table>\n";
      return(
$table);
   }
   
   
/**
   *  array getArray()
   *  Purpose: get query results as an array
   */
   
function getArray()
   {
      
mysql_data_seek($this->result0);
      
$data = array();
      while(
$row mysql_fetch_assoc($this->result))
      {
         
$data[] = $row;
      }
      return(
$data);
   }  
// end getArray()
   
   /**
   *  str getXml()
   *  Purpose: get query results as an XML string
   */
   
function getXml()
   {
      
mysql_data_seek($this->result0);
      
$xml "<?xml version='1.0' encoding='ISO-8859-1'?>\n<data>\n";
      
$count 1;
      while(
$row mysql_fetch_assoc($this->result))
      {
         
$xml .= "  <record row='$count'>\n";
         foreach(
$row as $key => $val)
         {
            
$xml .= "    <$key>$val</$key>\n";
         }
         
$xml .= "  </record>\n";
         
$count++;
      }
      
$xml .= "</data>";
      return(
$xml);
   }  
// end getXml()
   
   /**
   *  bool free()
   *  Purpose: free this MySQL result
   */
   
function free()
   {
      return(
mysql_free_result($this->result));
   }  
// end free()
   
}  // end class QueryResult