Source for file DataBaseConnector.class.php

Documentation is available at DataBaseConnector.class.php

  1. <?php
  2.   /**
  3.     * Encapsulates databse functions.
  4.     *
  5.     * This class encapsulates all of the functions for connecting to the database.
  6.     * @author Richard Sharp
  7.     * @copyright 2011
  8.     * @package Database
  9. */
  10. {
  11.       /**
  12.         * Encapsulates database functions..
  13.         *
  14.         * This class encapsulates all of the functions for connecting to the database.
  15.         * @author Richard Sharp
  16.         * @copyright 2010
  17.         * @package Database
  18.     */
  19.     
  20.     /********************************* Public Variables **********************************************/
  21.     
  22.     /**
  23.      * Gets or sets whether or not to automaticllay update the Modified and Created fields in the  table (must be those exact names).
  24.      *    @var boolean 
  25.      */
  26.     public $UpdateTimestamps=true;
  27.     
  28.     /**
  29.      * Gets or sets the database name.
  30.      *    @var string 
  31.      */
  32.     public $DatabaseName="";
  33.     
  34.     /**
  35.      * Gets or sets the database host. Default is localhost.
  36.      *    @var string 
  37.      */
  38.     public $Host="localhost";
  39.     
  40.     /**
  41.      * Gets the raw text of the last query performed.
  42.      *    @var string 
  43.      */
  44.     public $LastQuery="";
  45.     
  46.     /**
  47.      * If set, an error log will be written to this file. Use a full file path.
  48.      *    @var string 
  49.      */
  50.     public $LogFile="";
  51.     
  52.     /**
  53.      * Gets or sets the database password.
  54.      *    @var string 
  55.      */
  56.     public $Password="";
  57.     
  58.     /**
  59.      * Gets or sets the database username.
  60.      *    @var string 
  61.      */
  62.     public $Username="";
  63.     
  64.     /********************************* Private Variables **********************************************/
  65.     /*
  66.     * @access private
  67.     * This is a mysqli class instance.
  68.     */
  69.     private $objConnection;
  70.     
  71.     
  72.     /********************************* Methods **********************************************/
  73.     
  74.      /**
  75.      * Constructor for the class.
  76.      * @param string The database username.
  77.      * @param string The database password.
  78.      * @param string The database name.
  79.      * @param string The database host.
  80.      * @return void 
  81.      */ 
  82.     function __construct($Username="",$Password="",$DatabaseName="",$Host="")
  83.     {
  84.         if(isset($Host)) $this->Host=$Host;
  85.         else $this->Host="localhost";
  86.         if(isset($Username)) $this->Username=$Username;
  87.         if(isset($Password)) $this->Password=$Password;
  88.         if($DatabaseName!=""$this->DatabaseName=$DatabaseName;
  89.     }
  90.     
  91.     /**
  92.      * Destructor for the class.
  93.      * @return void 
  94.      */ 
  95.      function __destruct()
  96.      {
  97.          try
  98.         {
  99.             if($this->objConnection$this->objConnection->Close();
  100.         }
  101.         catch(Exception $e){}
  102.      }
  103.     
  104.     /**
  105.      * Connects to the database. Returns true on success, or false on failure.
  106.      * @return void 
  107.      * @access private
  108.      */ 
  109.     private function Connect($bRedirect=false)
  110.     {
  111.         try
  112.         {
  113.             //make sure to release any previous connection.
  114.             unset($this->objConnection);
  115.             //create a new mysqli class and connect.
  116.             $objConnection=new mysqli($this->Host,$this->Username,$this->Password,$this->DatabaseName);
  117.             //check for connection error
  118.             if($objConnection->connect_error)
  119.             {
  120.                 throw new Exception("MySQL Connection Failure: ".$objConnection->connect_error);
  121.             }
  122.             //check for connection error prior to  PHP 5.2.9
  123.             if (mysqli_connect_error()) 
  124.             {
  125.                 throw new Exception("MySQL Connection Failure: ".mysqli_connect_error());
  126.             }
  127.             //no error, so return the object and store a reference.
  128.             $this->objConnection=$objConnection;
  129.             return true;
  130.         
  131.         catch(Exception $e)
  132.         {
  133.             //log the error
  134.             $this->LogError("MySQL Connection Failure: ".$e->getMessage());
  135.             return false;
  136.         }
  137.     }
  138.     /**
  139.     * Escapes the value to be placed in a field. This helps prevent problems with quotes, and mitigates SQL injection attacks.
  140.     * @param string The value to escape.
  141.     * @return string 
  142.     */
  143.     public function Escape($Value)
  144.     {
  145.         if($this->TestConnection())
  146.         {
  147.             return($this->objConnection->real_escape_string($Value));
  148.         }
  149.         else return(false);
  150.     }
  151.     
  152.     /**
  153.     * Returns the number of rows affected by the previous query
  154.     * @return int 
  155.     */
  156.     public function GetAffectedRows()
  157.     {
  158.         if(!$this->objConnectionreturn 0;
  159.         return($this->objConnection->affected_rows);
  160.     }
  161.     
  162.      /**
  163.      * Gets the text of the last error, if any.
  164.      * @return string 
  165.      */ 
  166.     public function GetLastError()
  167.     {
  168.         if(!$this->objConnectionreturn "";
  169.         return($this->objConnection->error);
  170.     }
  171.     
  172.     /**
  173.      * Inserts a record into the database. Returns the insert auto-incremented ID on success, false on failure. Unless UpdateTimestamps is set to false, fields will automatically be added for Modified and Created.
  174.      * @param string The name of the table.
  175.      * @param array An array of the fields/values to insert. Each element key is the column name for the table, and the value is the value to insert.
  176.      * @return int 
  177.      */ 
  178.     public function Insert($Table,$Fields)
  179.     {
  180.         try
  181.         {
  182.             if(!is_array($Fields)) throw new Exception("Attempted to insert with no fields.");
  183.             if(true===$this->TestConnection())
  184.             {
  185.                 foreach($Fields as $sKey => $sValue)
  186.                 {
  187.                     $aKeys[]=$sKey;
  188.                     if(substr_count($sValue,"password(")>0$aValues[]=$sValue//if we are using the password function, don't escape or add quotes.
  189.                     elseif(strtolower($sValue)=="null"$aValues[]="NULL"//if we are setting a field to NULL, don't escape or add quotes.
  190.                     else $aValues[]='"'.$this->Escape($sValue).'"'//escape and add quotes
  191.                 }
  192.                 $sQuery='INSERT INTO '.$Table.' ('.implode(",",$aKeys);
  193.                 if($this->UpdateTimestamps$sQuery.=',Modified,Created';
  194.                 $sQuery.=') VALUES ('.implode(',',$aValues);
  195.                 if($this->UpdateTimestamps$sQuery.=',now(),now()';
  196.                 $sQuery.=')';
  197.                 $this->LastQuery=$sQuery;
  198.                 $bResult=$this->objConnection->query($sQuery);
  199.                 if(true==$bResultreturn($this->objConnection->insert_id);
  200.                 else throw new Exception("Insert Failed: ".$sQuery." Error: ".$this->objConnection->error);
  201.             }
  202.             else return(false);
  203.         }
  204.         catch(Exception $e)
  205.         {
  206.             $this->LogError($e->getMessage());
  207.             return false;
  208.         }
  209.     }
  210.     
  211.      /**
  212.      * Runs a raw query on the database that does not expect any return. Returns the result of that query, which may be a boolean for failure or an object for success of some queries.
  213.      * @param string The query to run.
  214.      * @return mixed 
  215.      */ 
  216.     public function Query($Query)
  217.     {
  218.         try
  219.         {
  220.             if($this->TestConnection())
  221.             {
  222.                 $this->LastQuery=$Query;
  223.                 $oResult=$this->objConnection->query($Query);
  224.                 if(false==$oResultthrow new Exception("Query failed: $query Error: ".$objConnection->error);
  225.                 else return $oResult;
  226.             }
  227.             else throw new Exception("Connection Failed.");
  228.         }
  229.         catch(Exception $e)
  230.         {
  231.             $this->LogError($e->getMessage());
  232.             return false;
  233.         }
  234.     }
  235.     
  236.      /**
  237.      * Performs an Update query on the database. Returns true on success, false on failure.
  238.      * @param string The name of the table.
  239.      * @param array An associative array of the fields to update. Each element's key is the column name in the table, and the value of the element is the value to update.
  240.      * @param boolean Whether or not to use delayed replace. Default false.
  241.      * @return bool 
  242.      */ 
  243.     public function Replace($Table,$Fields,$Delayed=false)
  244.     {
  245.         try
  246.         {
  247.             if(!is_array($Fields)) throw new Exception("Attempted to update with no fields selected");
  248.             if($this->TestConnection())
  249.             {
  250.                 foreach($Fields as $sKey => $sValue)
  251.                 {
  252.                     $aKeys[]=$sKey;
  253.                     if(substr_count($sValue,"password(")>0$aValues[]=$sValue//if we are using the password function, don't escape or add quotes.
  254.                     elseif(strtolower($sValue)=="null"$aValues[]="NULL"//if we are setting a field to NULL, don't escape or add quotes.
  255.                     else $aValues[]='"'.$this->Escape($sValue).'"'//escape and add quotes
  256.                 }
  257.                 $sQuery='REPLACE'.(true===$Delayed?" DELAYED":"").' INTO '.$Table.' ('.implode(",",$aKeys);
  258.                 if(true===$this->UpdateTimestamps$sQuery.=',Modified,Created';
  259.                 $sQuery.=') VALUES ('.implode(',',$aValues);
  260.                 if(true===$this->UpdateTimestamps$sQuery.=',now(),now()';
  261.                 $sQuery.=')';
  262.                 $this->LastQuery=$sQuery;
  263.                 $bResult=$this->objConnection->query($sQuery);
  264.                 if(true==$bResultreturn true;
  265.                 else throw new Exception("Replace Failed: ".$sQuery." Error: ".$this->objConnection->error);
  266.             }
  267.             else throw new Exception("Failed to conenct to database.");
  268.         }
  269.         catch(Exception $e)
  270.         {
  271.             $this->LogError($e->getMessage());
  272.             return false;
  273.         }
  274.     }
  275.     
  276.      /**
  277.      * Runs a Select query on the database. Returns an associative array of rows on success, false on failure. This will also loop through all of the results and clean the data (stripslashes).
  278.      * @param string The query to run.
  279.      * @return mixed 
  280.      */ 
  281.     public function Select($Query)
  282.     {
  283.         try
  284.         {
  285.             if($this->TestConnection())
  286.             {
  287.                 $this->LastQuery=$Query;
  288.                 $oResult=$this->objConnection->query($Query);
  289.                 if(false===$oResultthrow new Exception("Select failed: $Query Error: ".$this->objConnection->error);
  290.                 while($aRow=$oResult->fetch_assoc())
  291.                 {
  292.                     foreach($aRow as $sKey => $sValue$aRow[$sKey]=stripslashes($sValue);
  293.                     $aReturn[]=$aRow;
  294.                 }
  295.             }
  296.             else throw new Exception("Failed to connect to database.");
  297.             return($aReturn);
  298.         }
  299.         catch(Exception $e)
  300.         {
  301.             $this->LogError($e->getMessage());
  302.             return false;
  303.         }
  304.     }
  305.     
  306.      /**
  307.      * Tests to make sure the connection to the database is open, and if not, attempts to re-open the connection.
  308.      * @return bool 
  309.      */ 
  310.     public function TestConnection()
  311.     {
  312.         try
  313.         {
  314.             if(!$this->objConnection
  315.             {
  316.                 if(false===$this->Connect()) throw new Exception("Failed to connect in TestConnection.");
  317.             }
  318.             if(false===$this->objConnection->ping()) throw new Exception("Failed to ping connection in TestConnection.");
  319.             return(true);
  320.         }
  321.         catch(Exception $e)
  322.         {
  323.             $this->LogError($e->getMessage());
  324.             return false;
  325.         }
  326.     }
  327.     
  328.      /**
  329.      * Performs an Update query on the database. Returns success or failure.
  330.      * @param string The name of the table.
  331.      * @param array An associative array of the fields to update. Each element's key is the column name in the table, and the value of the element is the value to update.
  332.      * @param string The WHERE clause of the query.
  333.      * @param int Optional. The limit to the number of rows that should be affected.
  334.      * @return bool 
  335.      */ 
  336.     public function Update($Table,$Fields,$Condition,$Limit=0)
  337.     {
  338.         try
  339.         {
  340.             if(!is_array($Fields)) throw new Exception("Tried to update with an empty field list.");
  341.             if(true===$this->TestConnection())
  342.             {
  343.                 foreach($Fields as $sKey => $sValue
  344.                 {
  345.                     if(substr_count($sValue,"password(")>0$aUpdates[]=$sKey.'='.$sValue//if we are using the password function, don't escape or add quotes.
  346.                     elseif(strtolower($sValue)=="null"$aValues[]="NULL";  //if we are setting a field to NULL, don't escape or add quotes.
  347.                     else $aUpdates[]=$sKey.'="'.$this->objConnection->real_escape_string($sValue).'"'//escape and add quotes
  348.                 }
  349.                 $sQuery='UPDATE '.$Table.' SET '.implode(",",$aUpdates);
  350.                 if($this->UpdateTimestamps$sQuery.=',Modified=now() ';
  351.                 $sQuery.=' WHERE '.$Condition;
  352.                 if($Limit$sQuery.=' LIMIT '.$Limit;
  353.                 $this->LastQuery=$sQuery;
  354.                 $bResult=$this->objConnection->query($sQuery);
  355.                 if(true==$bResultreturn true;
  356.                 else throw new Exception("Replace Failed: ".$sQuery." Error: ".$this->objConnection->error);
  357.             }
  358.             else throw new Exception("Failed to connect to database.");
  359.         }
  360.         catch(Exception $e)
  361.         {
  362.             $this->LogError($e->getMessage());
  363.             return false;
  364.         }
  365.     }
  366.     
  367.     
  368.     
  369.     private function LogError($ErrorText)
  370.     {
  371.         if($this->LogFile!="")
  372.         {
  373.             try
  374.             {
  375.                 $oFile=@fopen($this->LogFile,"a");
  376.                 if($oFile)
  377.                 {
  378.                     $message=date("m/d/y H:i:s")."\n".$ErrorText."\n--------------------------------------------------------------------\n";
  379.                     fputs($oFile,$message,strlen($message));
  380.                     fclose($oFile);
  381.                 }
  382.             }
  383.             catch(Exception $e){}
  384.         }
  385.     }
  386. }
  387. ?>

Documentation generated on Wed, 26 Jan 2011 15:24:43 -0700 by phpDocumentor 1.4.3