Guest User

Untitled

a guest
Mar 23rd, 2013
70
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 52.17 KB | None | 0 0
  1. <?php
  2. /**
  3.  * Ultimate MySQL Wrapper Class
  4.  *
  5.  * @version 2.5.1
  6.  * @author Jeff L. Williams
  7.  * @link http://www.phpclasses.org/ultimatemysql
  8.  *
  9.  * Contributions from
  10.  *   Frank P. Walentynowicz
  11.  *   Larry Wakeman
  12.  *   Nicola Abbiuso
  13.  *   Douglas Gintz
  14.  *   Emre Erkan
  15.  *   Vincent van Daal
  16.  */
  17. class MySQL
  18. {
  19.     // SET THESE VALUES TO MATCH YOUR DATA CONNECTION
  20.     private $db_host    = "localhost";  // server name
  21.     private $db_user    = "";       // user name
  22.     private $db_pass    = "";           // password
  23.     private $db_dbname  = "";           // database name
  24.     private $db_charset = "";           // optional character set (i.e. utf8)
  25.     private $db_pcon    = false;        // use persistent connection?
  26.     public  $table_prefix = "";
  27.  
  28.     // constants for SQLValue function
  29.     const SQLVALUE_BIT      = "bit";
  30.     const SQLVALUE_BOOLEAN  = "boolean";
  31.     const SQLVALUE_DATE     = "date";
  32.     const SQLVALUE_DATETIME = "datetime";
  33.     const SQLVALUE_NUMBER   = "number";
  34.     const SQLVALUE_T_F      = "t-f";
  35.     const SQLVALUE_TEXT     = "text";
  36.     const SQLVALUE_TIME     = "time";
  37.     const SQLVALUE_Y_N      = "y-n";
  38.  
  39.     // class-internal variables - do not change
  40.     private $active_row     = -1;       // current row
  41.     private $error_desc     = "";       // last mysql error string
  42.     private $error_number   = 0;        // last mysql error number
  43.     private $in_transaction = false;    // used for transactions
  44.     private $last_insert_id;            // last id of record inserted
  45.     private $last_result;               // last mysql query result
  46.     private $last_sql       = "";       // last mysql query
  47.     private $mysql_link     = 0;        // mysql link resource
  48.     private $time_diff      = 0;        // holds the difference in time
  49.     private $time_start     = 0;        // start time for the timer
  50.  
  51.     /**
  52.      * Determines if an error throws an exception
  53.      *
  54.      * @var boolean Set to true to throw error exceptions
  55.      */
  56.     public $ThrowExceptions = false;
  57.  
  58.     /**
  59.      * Constructor: Opens the connection to the database
  60.      *
  61.      * @param boolean $connect (Optional) Auto-connect when object is created
  62.      * @param string $database (Optional) Database name
  63.      * @param string $server   (Optional) Host address
  64.      * @param string $username (Optional) User name
  65.      * @param string $password (Optional) Password
  66.      * @param string $charset  (Optional) Character set
  67.      */
  68.     public function __construct($connect = true, $database = null, $server = null,
  69.                                 $username = null, $password = null, $charset = null) {
  70.  
  71.         if ($database !== null) $this->db_dbname  = $database;
  72.         if ($server   !== null) $this->db_host    = $server;
  73.         if ($username !== null) $this->db_user    = $username;
  74.         if ($password !== null) $this->db_pass    = $password;
  75.         if ($charset  !== null) $this->db_charset = $charset;
  76.  
  77.         if (strlen($this->db_host) > 0 &&
  78.             strlen($this->db_user) > 0) {
  79.             if ($connect) $this->Open();
  80.         }
  81.     }
  82.  
  83.     /**
  84.      * Destructor: Closes the connection to the database
  85.      *
  86.      */
  87.     public function __destruct() {
  88.         $this->Close();
  89.     }
  90.  
  91.     /**
  92.      * Automatically does an INSERT or UPDATE depending if an existing record
  93.      * exists in a table
  94.      *
  95.      * @param string $tableName The name of the table
  96.      * @param array $valuesArray An associative array containing the column
  97.      *                            names as keys and values as data. The values
  98.      *                            must be SQL ready (i.e. quotes around
  99.      *                            strings, formatted dates, ect)
  100.      * @param array $whereArray An associative array containing the column
  101.      *                           names as keys and values as data. The values
  102.      *                           must be SQL ready (i.e. quotes around strings,
  103.      *                           formatted dates, ect).
  104.      * @return boolean Returns TRUE on success or FALSE on error
  105.      */
  106.     public function AutoInsertUpdate($tableName, $valuesArray, $whereArray) {
  107.         $this->ResetError();
  108.         $this->SelectRows($tableName, $whereArray);
  109.         if (! $this->Error()) {
  110.             if ($this->HasRecords()) {
  111.                 return $this->UpdateRows($tableName, $valuesArray, $whereArray);
  112.             } else {
  113.                 return $this->InsertRow($tableName, $valuesArray);
  114.             }
  115.         } else {
  116.             return false;
  117.         }
  118.     }
  119.  
  120.     /**
  121.      * Returns true if the internal pointer is at the beginning of the records
  122.      *
  123.      * @return boolean TRUE if at the first row or FALSE if not
  124.      */
  125.     public function BeginningOfSeek() {
  126.         $this->ResetError();
  127.         if ($this->IsConnected()) {
  128.             if ($this->active_row < 1) {
  129.                 return true;
  130.             } else {
  131.                 return false;
  132.             }
  133.         } else {
  134.             $this->SetError("No connection");
  135.             return false;
  136.         }
  137.     }
  138.  
  139.     /**
  140.      * [STATIC] Builds a comma delimited list of columns for use with SQL
  141.      *
  142.      * @param array $valuesArray An array containing the column names.
  143.      * @param boolean $addQuotes (Optional) TRUE to add quotes
  144.      * @param boolean $showAlias (Optional) TRUE to show column alias
  145.      * @return string Returns the SQL column list
  146.      */
  147.     static private function BuildSQLColumns($columns, $addQuotes = true, $showAlias = true) {
  148.         if ($addQuotes) {
  149.             $quote = "`";
  150.         } else {
  151.             $quote = "";
  152.         }
  153.         switch (gettype($columns)) {
  154.             case "array":
  155.                 $sql = "";
  156.                 foreach ($columns as $key => $value) {
  157.                     // Build the columns
  158.                     if (strlen($sql) == 0) {
  159.                         $sql = $quote . $value . $quote;
  160.                     } else {
  161.                         $sql .= ", " . $quote . $value . $quote;
  162.                     }
  163.                     if ($showAlias && is_string($key) && (! empty($key))) {
  164.                         $sql .= ' AS "' . $key . '"';
  165.                     }
  166.                 }
  167.                 return $sql;
  168.                 break;
  169.             case "string":
  170.                 return $quote . $columns . $quote;
  171.                 break;
  172.             default:
  173.                 return false;
  174.                 break;
  175.         }
  176.     }
  177.  
  178.     /**
  179.      * [STATIC] Builds a SQL DELETE statement
  180.      *
  181.      * @param string $tableName The name of the table
  182.      * @param array $whereArray (Optional) An associative array containing the
  183.      *                           column names as keys and values as data. The
  184.      *                           values must be SQL ready (i.e. quotes around
  185.      *                           strings, formatted dates, ect). If not specified
  186.      *                           then all values in the table are deleted.
  187.      * @return string Returns the SQL DELETE statement
  188.      */
  189.     static public function BuildSQLDelete($tableName, $whereArray = null) {
  190.         $sql = "DELETE FROM `" . $tableName . "`";
  191.         if (! is_null($whereArray)) {
  192.             $sql .= self::BuildSQLWhereClause($whereArray);
  193.         }
  194.         return $sql;
  195.     }
  196.  
  197.     /**
  198.      * [STATIC] Builds a SQL INSERT statement
  199.      *
  200.      * @param string $tableName The name of the table
  201.      * @param array $valuesArray An associative array containing the column
  202.      *                            names as keys and values as data. The values
  203.      *                            must be SQL ready (i.e. quotes around
  204.      *                            strings, formatted dates, ect)
  205.      * @return string Returns a SQL INSERT statement
  206.      */
  207.     static public function BuildSQLInsert($tableName, $valuesArray) {
  208.         $columns = self::BuildSQLColumns(array_keys($valuesArray));
  209.         $values  = self::BuildSQLColumns($valuesArray, false, false);
  210.         $sql = "INSERT INTO `" . $tableName .
  211.                "` (" . $columns . ") VALUES (" . $values . ")";
  212.         return $sql;
  213.     }
  214.  
  215.     /**
  216.      * Builds a simple SQL SELECT statement
  217.      *
  218.      * @param string $tableName The name of the table
  219.      * @param array $whereArray (Optional) An associative array containing the
  220.      *                          column names as keys and values as data. The
  221.      *                          values must be SQL ready (i.e. quotes around
  222.      *                          strings, formatted dates, ect)
  223.      * @param array/string $columns (Optional) The column or list of columns to select
  224.      * @param array/string $sortColumns (Optional) Column or list of columns to sort by
  225.      * @param boolean $sortAscending (Optional) TRUE for ascending; FALSE for descending
  226.      *                               This only works if $sortColumns are specified
  227.      * @param integer/string $limit (Optional) The limit of rows to return
  228.      * @return string Returns a SQL SELECT statement
  229.      */
  230.     static public function BuildSQLSelect($tableName, $whereArray = null, $columns = null,
  231.                                           $sortColumns = null, $sortAscending = true, $limit = null) {
  232.         if (! is_null($columns)) {
  233.             $sql = self::BuildSQLColumns($columns);
  234.         } else {
  235.             $sql = "*";
  236.         }
  237.         $sql = "SELECT " . $sql . " FROM `" . $tableName . "`";
  238.         if (is_array($whereArray)) {
  239.             $sql .= self::BuildSQLWhereClause($whereArray);
  240.         }
  241.         if (! is_null($sortColumns)) {
  242.             $sql .= " ORDER BY " .
  243.                     self::BuildSQLColumns($sortColumns, true, false) .
  244.                     " " . ($sortAscending ? "ASC" : "DESC");
  245.         }
  246.         if (! is_null($limit)) {
  247.             $sql .= " LIMIT " . $limit;
  248.         }
  249.         return $sql;
  250.     }
  251.  
  252.     /**
  253.      * [STATIC] Builds a SQL UPDATE statement
  254.      *
  255.      * @param string $tableName The name of the table
  256.      * @param array $valuesArray An associative array containing the column
  257.      *                            names as keys and values as data. The values
  258.      *                            must be SQL ready (i.e. quotes around
  259.      *                            strings, formatted dates, ect)
  260.      * @param array $whereArray (Optional) An associative array containing the
  261.      *                           column names as keys and values as data. The
  262.      *                           values must be SQL ready (i.e. quotes around
  263.      *                           strings, formatted dates, ect). If not specified
  264.      *                           then all values in the table are updated.
  265.      * @return string Returns a SQL UPDATE statement
  266.      */
  267.     static public function BuildSQLUpdate($tableName, $valuesArray, $whereArray = null) {
  268.         $sql = "";
  269.         foreach ($valuesArray as $key => $value) {
  270.             if (strlen($sql) == 0) {
  271.                 $sql = "`" . $key . "` = " . $value;
  272.             } else {
  273.                 $sql .= ", `" . $key . "` = " . $value;
  274.             }
  275.         }
  276.         $sql = "UPDATE `" . $tableName . "` SET " . $sql;
  277.         if (is_array($whereArray)) {
  278.             $sql .= self::BuildSQLWhereClause($whereArray);
  279.         }
  280.         return $sql;
  281.     }
  282.  
  283.     /**
  284.      * [STATIC] Builds a SQL WHERE clause from an array.
  285.      * If a key is specified, the key is used at the field name and the value
  286.      * as a comparison. If a key is not used, the value is used as the clause.
  287.      *
  288.      * @param array $whereArray An associative array containing the column
  289.      *                           names as keys and values as data. The values
  290.      *                           must be SQL ready (i.e. quotes around
  291.      *                           strings, formatted dates, ect)
  292.      * @return string Returns a string containing the SQL WHERE clause
  293.      */
  294.     static public function BuildSQLWhereClause($whereArray) {
  295.         $where = "";
  296.         foreach ($whereArray as $key => $value) {
  297.             if (strlen($where) == 0) {
  298.                 if (is_string($key)) {
  299.                     $where = " WHERE `" . $key . "` = " . $value;
  300.                 } else {
  301.                     $where = " WHERE " . $value;
  302.                 }
  303.             } else {
  304.                 if (is_string($key)) {
  305.                     $where .= " AND `" . $key . "` = " . $value;
  306.                 } else {
  307.                     $where .= " AND " . $value;
  308.                 }
  309.             }
  310.         }
  311.         return $where;
  312.     }
  313.  
  314.     /**
  315.      * Close current MySQL connection
  316.      *
  317.      * @return object Returns TRUE on success or FALSE on error
  318.      */
  319.     public function Close() {
  320.         $this->ResetError();
  321.         $this->active_row = -1;
  322.         $success = $this->Release();
  323.         if ($success) {
  324.             $success = @mysql_close($this->mysql_link);
  325.             if (! $success) {
  326.                 $this->SetError();
  327.             } else {
  328.                 unset($this->last_sql);
  329.                 unset($this->last_result);
  330.                 unset($this->mysql_link);
  331.             }
  332.         }
  333.         return $success;
  334.     }
  335.  
  336.     /**
  337.      * Deletes rows in a table based on a WHERE filter
  338.      * (can be just one or many rows based on the filter)
  339.      *
  340.      * @param string $tableName The name of the table
  341.      * @param array $whereArray (Optional) An associative array containing the
  342.      *                          column names as keys and values as data. The
  343.      *                          values must be SQL ready (i.e. quotes around
  344.      *                          strings, formatted dates, ect). If not specified
  345.      *                          then all values in the table are deleted.
  346.      * @return boolean Returns TRUE on success or FALSE on error
  347.      */
  348.     public function DeleteRows($tableName, $whereArray = null) {
  349.         $this->ResetError();
  350.         if (! $this->IsConnected()) {
  351.             $this->SetError("No connection");
  352.             return false;
  353.         } else {
  354.             $sql = self::BuildSQLDelete($tableName, $whereArray);
  355.             // Execute the UPDATE
  356.             if (! $this->Query($sql)) {
  357.                 return false;
  358.             } else {
  359.                 return true;
  360.             }
  361.         }
  362.     }
  363.  
  364.     /**
  365.      * Returns true if the internal pointer is at the end of the records
  366.      *
  367.      * @return boolean TRUE if at the last row or FALSE if not
  368.      */
  369.     public function EndOfSeek() {
  370.         $this->ResetError();
  371.         if ($this->IsConnected()) {
  372.             if ($this->active_row >= ($this->RowCount())) {
  373.                 return true;
  374.             } else {
  375.                 return false;
  376.             }
  377.         } else {
  378.             $this->SetError("No connection");
  379.             return false;
  380.         }
  381.     }
  382.  
  383.     /**
  384.      * Returns the last MySQL error as text
  385.      *
  386.      * @return string Error text from last known error
  387.      */
  388.     public function Error() {
  389.         $error = $this->error_desc;
  390.         if (empty($error)) {
  391.             if ($this->error_number <> 0) {
  392.                 $error = "Unknown Error (#" . $this->error_number . ")";
  393.             } else {
  394.                 $error = false;
  395.             }
  396.         } else {
  397.             if ($this->error_number > 0) {
  398.                 $error .= " (#" . $this->error_number . ")";
  399.             }
  400.         }
  401.         return $error;
  402.     }
  403.  
  404.     /**
  405.      * Returns the last MySQL error as a number
  406.      *
  407.      * @return integer Error number from last known error
  408.      */
  409.     public function ErrorNumber() {
  410.         if (strlen($this->error_desc) > 0)
  411.         {
  412.             if ($this->error_number <> 0)
  413.             {
  414.                 return $this->error_number;
  415.             } else {
  416.                 return -1;
  417.             }
  418.         } else {
  419.             return $this->error_number;
  420.         }
  421.     }
  422.  
  423.     /**
  424.      * [STATIC] Converts any value of any datatype into boolean (true or false)
  425.      *
  426.      * @param mixed $value Value to analyze for TRUE or FALSE
  427.      * @return boolean Returns TRUE or FALSE
  428.      */
  429.     static public function GetBooleanValue($value) {
  430.         if (gettype($value) == "boolean") {
  431.             if ($value == true) {
  432.                 return true;
  433.             } else {
  434.                 return false;
  435.             }
  436.         } elseif (is_numeric($value)) {
  437.             if ($value > 0) {
  438.                 return true;
  439.             } else {
  440.                 return false;
  441.             }
  442.         } else {
  443.             $cleaned = strtoupper(trim($value));
  444.  
  445.             if ($cleaned == "ON") {
  446.                 return true;
  447.             } elseif ($cleaned == "SELECTED" || $cleaned == "CHECKED") {
  448.                 return true;
  449.             } elseif ($cleaned == "YES" || $cleaned == "Y") {
  450.                 return true;
  451.             } elseif ($cleaned == "TRUE" || $cleaned == "T") {
  452.                 return true;
  453.             } else {
  454.                 return false;
  455.             }
  456.         }
  457.     }
  458.  
  459.     /**
  460.      * Returns the comments for fields in a table into an
  461.      * array or NULL if the table has not got any fields
  462.      *
  463.      * @param string $table Table name
  464.      * @return array An array that contains the column comments
  465.      */
  466.     public function GetColumnComments($table) {
  467.         $this->ResetError();
  468.         $records = mysql_query("SHOW FULL COLUMNS FROM " . $table);
  469.         if (! $records) {
  470.             $this->SetError();
  471.             return false;
  472.         } else {
  473.             // Get the column names
  474.             $columnNames = $this->GetColumnNames($table);
  475.             if ($this->Error()) {
  476.                 return false;
  477.             } else {
  478.                 $index = 0;
  479.                 // Fetchs the array to be returned (column 8 is field comment):
  480.                 while ($array_data = mysql_fetch_array($records)) {
  481.                     $columns[$index] = $array_data[8];
  482.                     $columns[$columnNames[$index++]] = $array_data[8];
  483.                 }
  484.                 return $columns;
  485.             }
  486.         }
  487.     }
  488.  
  489.     /**
  490.      * This function returns the number of columns or returns FALSE on error
  491.      *
  492.      * @param string $table (Optional) If a table name is not specified, the
  493.      *                      column count is returned from the last query
  494.      * @return integer The total count of columns
  495.      */
  496.     public function GetColumnCount($table = "") {
  497.         $this->ResetError();
  498.         if (empty($table)) {
  499.             $result = mysql_num_fields($this->last_result);
  500.             if (! $result) $this->SetError();
  501.         } else {
  502.             $records = mysql_query("SELECT * FROM " . $table . " LIMIT 1");
  503.             if (! $records) {
  504.                 $this->SetError();
  505.                 $result = false;
  506.             } else {
  507.                 $result = mysql_num_fields($records);
  508.                 $success = @mysql_free_result($records);
  509.                 if (! $success) {
  510.                     $this->SetError();
  511.                     $result = false;
  512.                 }
  513.             }
  514.         }
  515.         return $result;
  516.     }
  517.  
  518.     /**
  519.      * This function returns the data type for a specified column. If
  520.      * the column does not exists or no records exist, it returns FALSE
  521.      *
  522.      * @param string $column Column name or number (first column is 0)
  523.      * @param string $table (Optional) If a table name is not specified, the
  524.      *                      last returned records are used
  525.      * @return string MySQL data (field) type
  526.      */
  527.     public function GetColumnDataType($column, $table = "") {
  528.         $this->ResetError();
  529.         if (empty($table)) {
  530.             if ($this->RowCount() > 0) {
  531.                 if (is_numeric($column)) {
  532.                     return mysql_field_type($this->last_result, $column);
  533.                 } else {
  534.                     return mysql_field_type($this->last_result, $this->GetColumnID($column));
  535.                 }
  536.             } else {
  537.                 return false;
  538.             }
  539.         } else {
  540.             if (is_numeric($column)) $column = $this->GetColumnName($column, $table);
  541.             $result = mysql_query("SELECT " . $column . " FROM " . $table . " LIMIT 1");
  542.             if (mysql_num_fields($result) > 0) {
  543.                 return mysql_field_type($result, 0);
  544.             } else {
  545.                 $this->SetError("The specified column or table does not exist, or no data was returned", -1);
  546.                 return false;
  547.             }
  548.         }
  549.     }
  550.  
  551.     /**
  552.      * This function returns the position of a column
  553.      *
  554.      * @param string $column Column name
  555.      * @param string $table (Optional) If a table name is not specified, the
  556.      *                      last returned records are used.
  557.      * @return integer Column ID
  558.      */
  559.     public function GetColumnID($column, $table = "") {
  560.         $this->ResetError();
  561.         $columnNames = $this->GetColumnNames($table);
  562.         if (! $columnNames) {
  563.             return false;
  564.         } else {
  565.             $index = 0;
  566.             $found = false;
  567.             foreach ($columnNames as $columnName) {
  568.                 if ($columnName == $column) {
  569.                     $found = true;
  570.                     break;
  571.                 }
  572.                 $index++;
  573.             }
  574.             if ($found) {
  575.                 return $index;
  576.             } else {
  577.                 $this->SetError("Column name not found", -1);
  578.                 return false;
  579.             }
  580.         }
  581.     }
  582.  
  583.    /**
  584.      * This function returns the field length or returns FALSE on error
  585.      *
  586.      * @param string $column Column name
  587.      * @param string $table (Optional) If a table name is not specified, the
  588.      *                      last returned records are used.
  589.      * @return integer Field length
  590.      */
  591.     public function GetColumnLength($column, $table = "") {
  592.         $this->ResetError();
  593.         if (empty($table)) {
  594.             if (is_numeric($column)) {
  595.                 $columnID = $column;
  596.             } else {
  597.                 $columnID = $this->GetColumnID($column);
  598.             }
  599.             if (! $columnID) {
  600.                 return false;
  601.             } else {
  602.                 $result = mysql_field_len($this->last_result, $columnID);
  603.                 if (! $result) {
  604.                     $this->SetError();
  605.                     return false;
  606.                 } else {
  607.                     return $result;
  608.                 }
  609.             }
  610.         } else {
  611.             $records = mysql_query("SELECT " . $column . " FROM " . $table . " LIMIT 1");
  612.             if (! $records) {
  613.                 $this->SetError();
  614.                 return false;
  615.             }
  616.             $result = mysql_field_len($records, 0);
  617.             if (! $result) {
  618.                 $this->SetError();
  619.                 return false;
  620.             } else {
  621.                 return $result;
  622.             }
  623.         }
  624.     }
  625.  
  626.    /**
  627.      * This function returns the name for a specified column number. If
  628.      * the index does not exists or no records exist, it returns FALSE
  629.      *
  630.      * @param string $columnID Column position (0 is the first column)
  631.      * @param string $table (Optional) If a table name is not specified, the
  632.      *                      last returned records are used.
  633.      * @return integer Field Length
  634.      */
  635.     public function GetColumnName($columnID, $table = "") {
  636.         $this->ResetError();
  637.         if (empty($table)) {
  638.             if ($this->RowCount() > 0) {
  639.                 $result = mysql_field_name($this->last_result, $columnID);
  640.                 if (! $result) $this->SetError();
  641.             } else {
  642.                 $result = false;
  643.             }
  644.         } else {
  645.             $records = mysql_query("SELECT * FROM " . $table . " LIMIT 1");
  646.             if (! $records) {
  647.                 $this->SetError();
  648.                 $result = false;
  649.             } else {
  650.                 if (mysql_num_fields($records) > 0) {
  651.                     $result = mysql_field_name($records, $columnID);
  652.                     if (! $result) $this->SetError();
  653.                 } else {
  654.                     $result = false;
  655.                 }
  656.             }
  657.         }
  658.         return $result;
  659.     }
  660.  
  661.     /**
  662.      * Returns the field names in a table or query in an array
  663.      *
  664.      * @param string $table (Optional) If a table name is not specified, the
  665.      *                      last returned records are used
  666.      * @return array An array that contains the column names
  667.      */
  668.     public function GetColumnNames($table = "") {
  669.         $this->ResetError();
  670.         if (empty($table)) {
  671.             $columnCount = mysql_num_fields($this->last_result);
  672.             if (! $columnCount) {
  673.                 $this->SetError();
  674.                 $columns = false;
  675.             } else {
  676.                 for ($column = 0; $column < $columnCount; $column++) {
  677.                     $columns[] = mysql_field_name($this->last_result, $column);
  678.                 }
  679.             }
  680.         } else {
  681.             $result = mysql_query("SHOW COLUMNS FROM " . $table);
  682.             if (! $result) {
  683.                 $this->SetError();
  684.                 $columns = false;
  685.             } else {
  686.                 while ($array_data = mysql_fetch_array($result)) {
  687.                     $columns[] = $array_data[0];
  688.                 }
  689.             }
  690.         }
  691.  
  692.         // Returns the array
  693.         return $columns;
  694.     }
  695.  
  696.     /**
  697.      * This function returns the last query as an HTML table
  698.      *
  699.      * @param boolean $showCount (Optional) TRUE if you want to show the row count,
  700.      *                           FALSE if you do not want to show the count
  701.      * @param string $styleTable (Optional) Style information for the table
  702.      * @param string $styleHeader (Optional) Style information for the header row
  703.      * @param string $styleData (Optional) Style information for the cells
  704.      * @return string HTML containing a table with all records listed
  705.      */
  706.     public function GetHTML($showCount = true, $styleTable = null, $styleHeader = null, $styleData = null) {
  707.         if ($styleTable === null) {
  708.             $tb = "border-collapse:collapse;empty-cells:show";
  709.         } else {
  710.             $tb = $styleTable;
  711.         }
  712.         if ($styleHeader === null) {
  713.             $th = "border-width:1px;border-style:solid;background-color:navy;color:white";
  714.         } else {
  715.             $th = $styleHeader;
  716.         }
  717.         if ($styleData === null) {
  718.             $td = "border-width:1px;border-style:solid";
  719.         } else {
  720.             $td = $styleData;
  721.         }
  722.  
  723.         if ($this->last_result) {
  724.             if ($this->RowCount() > 0) {
  725.                 $html = "";
  726.                 if ($showCount) $html = "Record Count: " . $this->RowCount() . "<br />\n";
  727.                 $html .= "<table style=\"$tb\" cellpadding=\"2\" cellspacing=\"2\">\n";
  728.                 $this->MoveFirst();
  729.                 $header = false;
  730.                 while ($member = mysql_fetch_object($this->last_result)) {
  731.                     if (!$header) {
  732.                         $html .= "\t<tr>\n";
  733.                         foreach ($member as $key => $value) {
  734.                             $html .= "\t\t<td style=\"$th\"><strong>" . htmlspecialchars($key) . "</strong></td>\n";
  735.                         }
  736.                         $html .= "\t</tr>\n";
  737.                         $header = true;
  738.                     }
  739.                     $html .= "\t<tr>\n";
  740.                     foreach ($member as $key => $value) {
  741.                         $html .= "\t\t<td style=\"$td\">" . htmlspecialchars($value) . "</td>\n";
  742.                     }
  743.                     $html .= "\t</tr>\n";
  744.                 }
  745.                 $this->MoveFirst();
  746.                 $html .= "</table>";
  747.             } else {
  748.                 $html = "No records were returned.";
  749.             }
  750.         } else {
  751.             $this->active_row = -1;
  752.             $html = false;
  753.         }
  754.         return $html;
  755.     }
  756.  
  757.     /**
  758.     * Returns the last query as a JSON document
  759.     *
  760.     * @return string JSON containing all records listed
  761.     */
  762.     public function GetJSON() {
  763.         if ($this->last_result) {
  764.             if ($this->RowCount() > 0) {
  765.                 for ($i = 0, $il = mysql_num_fields($this->last_result); $i < $il; $i++) {
  766.                     $types[$i] = mysql_field_type($this->last_result, $i);
  767.                 }
  768.                 $json = '[';
  769.                 $this->MoveFirst();
  770.                 while ($member = mysql_fetch_object($this->last_result)) {
  771.                     $json .= json_encode($member) . ",";
  772.                 }
  773.                 $json .= ']';
  774.                 $json = str_replace("},]", "}]", $json);
  775.             } else {
  776.                 $json = 'null';
  777.             }
  778.         } else {
  779.             $this->active_row = -1;
  780.             $json = 'null';
  781.         }
  782.         return $json;
  783.     }
  784.  
  785.     /**
  786.      * Returns the last autonumber ID field from a previous INSERT query
  787.      *
  788.      * @return  integer ID number from previous INSERT query
  789.      */
  790.     public function GetLastInsertID() {
  791.         return $this->last_insert_id;
  792.     }
  793.  
  794.     /**
  795.      * Returns the last SQL statement executed
  796.      *
  797.      * @return string Current SQL query string
  798.      */
  799.     public function GetLastSQL() {
  800.         return $this->last_sql;
  801.     }
  802.  
  803.     /**
  804.      * This function returns table names from the database
  805.      * into an array. If the database does not contains
  806.      * any tables, the returned value is FALSE
  807.      *
  808.      * @return array An array that contains the table names
  809.      */
  810.     public function GetTables() {
  811.         $this->ResetError();
  812.         // Query to get the tables in the current database:
  813.         $records = mysql_query("SHOW TABLES");
  814.         if (! $records) {
  815.             $this->SetError();
  816.             return FALSE;
  817.         } else {
  818.             while ($array_data = mysql_fetch_array($records)) {
  819.                 $tables[] = $array_data[0];
  820.             }
  821.  
  822.             // Returns the array or NULL
  823.             if (count($tables) > 0) {
  824.                 return $tables;
  825.             } else {
  826.                 return FALSE;
  827.             }
  828.         }
  829.     }
  830.  
  831.     /**
  832.      * Returns the last query as an XML Document
  833.      *
  834.      * @return string XML containing all records listed
  835.      */
  836.     public function GetXML() {
  837.         // Create a new XML document
  838.         $doc = new DomDocument('1.0'); // ,'UTF-8');
  839.  
  840.         // Create the root node
  841.         $root = $doc->createElement('root');
  842.         $root = $doc->appendChild($root);
  843.  
  844.         // If there was a result set
  845.         if (is_resource($this->last_result)) {
  846.  
  847.             // Show the row count and query
  848.             $root->setAttribute('rows',
  849.                 ($this->RowCount() ? $this->RowCount() : 0));
  850.             $root->setAttribute('query', $this->last_sql);
  851.             $root->setAttribute('error', "");
  852.  
  853.             // process one row at a time
  854.             $rowCount = 0;
  855.             while ($row = mysql_fetch_assoc($this->last_result)) {
  856.  
  857.                 // Keep the row count
  858.                 $rowCount = $rowCount + 1;
  859.  
  860.                 // Add node for each row
  861.                 $element = $doc->createElement('row');
  862.                 $element = $root->appendChild($element);
  863.                 $element->setAttribute('index', $rowCount);
  864.  
  865.                 // Add a child node for each field
  866.                 foreach ($row as $fieldname => $fieldvalue) {
  867.                     $child = $doc->createElement($fieldname);
  868.                     $child = $element->appendChild($child);
  869.  
  870.                     // $fieldvalue = iconv("ISO-8859-1", "UTF-8", $fieldvalue);
  871.                     $fieldvalue = htmlspecialchars($fieldvalue);
  872.                     $value = $doc->createTextNode($fieldvalue);
  873.                     $value = $child->appendChild($value);
  874.                 } // foreach
  875.             } // while
  876.         } else {
  877.             // Process any errors
  878.             $root->setAttribute('rows', 0);
  879.             $root->setAttribute('query', $this->last_sql);
  880.             if ($this->Error()) {
  881.                 $root->setAttribute('error', $this->Error());
  882.             } else {
  883.                 $root->setAttribute('error', "No query has been executed.");
  884.             }
  885.         }
  886.  
  887.         // Show the XML document
  888.         return $doc->saveXML();
  889.     }
  890.  
  891.     /**
  892.      * Determines if a query contains any rows
  893.      *
  894.      * @param string $sql [Optional] If specified, the query is first executed
  895.      *                    Otherwise, the last query is used for comparison
  896.      * @return boolean TRUE if records exist, FALSE if not or query error
  897.      */
  898.     public function HasRecords($sql = "") {
  899.         if (strlen($sql) > 0) {
  900.             $this->Query($sql);
  901.             if ($this->Error()) return false;
  902.         }
  903.         if ($this->RowCount() > 0) {
  904.             return true;
  905.         } else {
  906.             return false;
  907.         }
  908.     }
  909.  
  910.     /**
  911.      * Inserts a row into a table in the connected database
  912.      *
  913.      * @param string $tableName The name of the table
  914.      * @param array $valuesArray An associative array containing the column
  915.      *                            names as keys and values as data. The values
  916.      *                            must be SQL ready (i.e. quotes around
  917.      *                            strings, formatted dates, ect)
  918.      * @return integer Returns last insert ID on success or FALSE on failure
  919.      */
  920.     public function InsertRow($tableName, $valuesArray) {
  921.         $this->ResetError();
  922.         if (! $this->IsConnected()) {
  923.             $this->SetError("No connection");
  924.             return false;
  925.         } else {
  926.             // Execute the query
  927.             $sql = self::BuildSQLInsert($tableName, $valuesArray);
  928.             if (! $this->Query($sql)) {
  929.                 return false;
  930.             } else {
  931.                 return $this->GetLastInsertID();
  932.             }
  933.         }
  934.     }
  935.  
  936.     /**
  937.      * Determines if a valid connection to the database exists
  938.      *
  939.      * @return boolean TRUE idf connectect or FALSE if not connected
  940.      */
  941.     public function IsConnected() {
  942.         if (gettype($this->mysql_link) == "resource") {
  943.             return true;
  944.         } else {
  945.             return false;
  946.         }
  947.     }
  948.  
  949.     /**
  950.      * [STATIC] Determines if a value of any data type is a date PHP can convert
  951.      *
  952.      * @param date/string $value
  953.      * @return boolean Returns TRUE if value is date or FALSE if not date
  954.      */
  955.     static public function IsDate($value) {
  956.         $date = date('Y', strtotime($value));
  957.         if ($date == "1969" || $date == '') {
  958.             return false;
  959.         } else {
  960.             return true;
  961.         }
  962.     }
  963.  
  964.     /**
  965.      * Stop executing (die/exit) and show last MySQL error message
  966.      *
  967.      */
  968.     public function Kill($message = "") {
  969.         if (strlen($message) > 0) {
  970.             exit($message);
  971.         } else {
  972.             exit($this->Error());
  973.         }
  974.     }
  975.  
  976.     /**
  977.      * Seeks to the beginning of the records
  978.      *
  979.      * @return boolean Returns TRUE on success or FALSE on error
  980.      */
  981.     public function MoveFirst() {
  982.         $this->ResetError();
  983.         if (! $this->Seek(0)) {
  984.             $this->SetError();
  985.             return false;
  986.         } else {
  987.             $this->active_row = 0;
  988.             return true;
  989.         }
  990.     }
  991.  
  992.     /**
  993.      * Seeks to the end of the records
  994.      *
  995.      * @return boolean Returns TRUE on success or FALSE on error
  996.      */
  997.     public function MoveLast() {
  998.         $this->ResetError();
  999.         $this->active_row = $this->RowCount() - 1;
  1000.         if (! $this->Error()) {
  1001.             if (! $this->Seek($this->active_row)) {
  1002.                 return false;
  1003.             } else {
  1004.                 return true;
  1005.             }
  1006.         } else {
  1007.             return false;
  1008.         }
  1009.     }
  1010.  
  1011.     /**
  1012.      * Connect to specified MySQL server
  1013.      *
  1014.      * @param string $database (Optional) Database name
  1015.      * @param string $server   (Optional) Host address
  1016.      * @param string $username (Optional) User name
  1017.      * @param string $password (Optional) Password
  1018.      * @param string $charset  (Optional) Character set
  1019.      * @param boolean $pcon    (Optional) Persistant connection
  1020.      * @return boolean Returns TRUE on success or FALSE on error
  1021.      */
  1022.     public function Open($database = null, $server = null, $username = null,
  1023.                          $password = null, $charset = null, $pcon = false) {
  1024.         $this->ResetError();
  1025.  
  1026.         // Use defaults?
  1027.         if ($database !== null) $this->db_dbname  = $database;
  1028.         if ($server   !== null) $this->db_host    = $server;
  1029.         if ($username !== null) $this->db_user    = $username;
  1030.         if ($password !== null) $this->db_pass    = $password;
  1031.         if ($charset  !== null) $this->db_charset = $charset;
  1032.         if (is_bool($pcon))     $this->db_pcon    = $pcon;
  1033.  
  1034.         $this->active_row = -1;
  1035.  
  1036.         // Open persistent or normal connection
  1037.         if ($pcon) {
  1038.             $this->mysql_link = @mysql_pconnect(
  1039.                 $this->db_host, $this->db_user, $this->db_pass);
  1040.         } else {
  1041.             $this->mysql_link = @mysql_connect (
  1042.                 $this->db_host, $this->db_user, $this->db_pass);
  1043.         }
  1044.         // Connect to mysql server failed?
  1045.         if (! $this->IsConnected()) {
  1046.             $this->SetError();
  1047.             return false;
  1048.         } else {
  1049.             // Select a database (if specified)
  1050.             if (strlen($this->db_dbname) > 0) {
  1051.                 if (strlen($this->db_charset) == 0) {
  1052.                     if (! $this->SelectDatabase($this->db_dbname)) {
  1053.                         return false;
  1054.                     } else {
  1055.                         return true;
  1056.                     }
  1057.                 } else {
  1058.                     if (! $this->SelectDatabase(
  1059.                         $this->db_dbname, $this->db_charset)) {
  1060.                         return false;
  1061.                     } else {
  1062.                         return true;
  1063.                     }
  1064.                 }
  1065.             } else {
  1066.                 return true;
  1067.             }
  1068.         }
  1069.     }
  1070.  
  1071.     /**
  1072.      * Executes the given SQL query and returns the records
  1073.      *
  1074.      * @param string $sql The query string should not end with a semicolon
  1075.      * @return object PHP 'mysql result' resource object containing the records
  1076.      *                on SELECT, SHOW, DESCRIBE or EXPLAIN queries and returns;
  1077.      *                TRUE or FALSE for all others i.e. UPDATE, DELETE, DROP
  1078.      *                AND FALSE on all errors (setting the local Error message)
  1079.      */
  1080.     public function Query($sql) {
  1081.         $this->ResetError();
  1082.         $this->last_sql = $sql;
  1083.         $this->last_result = @mysql_query($sql, $this->mysql_link);
  1084.         if(! $this->last_result) {
  1085.             $this->active_row = -1;
  1086.             $this->SetError();
  1087.             return false;
  1088.         } else {
  1089.             if (strpos(strtolower($sql), "insert") === 0) {
  1090.                 $this->last_insert_id = mysql_insert_id();
  1091.                 if ($this->last_insert_id === false) {
  1092.                     $this->SetError();
  1093.                     return false;
  1094.                 } else {
  1095.                     $numrows = 0;
  1096.                     $this->active_row = -1;
  1097.                     return $this->last_result;
  1098.                 }
  1099.             } else if(strpos(strtolower($sql), "select") === 0) {
  1100.                 $numrows = mysql_num_rows($this->last_result);
  1101.                 if ($numrows > 0) {
  1102.                     $this->active_row = 0;
  1103.                 } else {
  1104.                     $this->active_row = -1;
  1105.                 }
  1106.                 $this->last_insert_id = 0;
  1107.                 return $this->last_result;
  1108.             } else {
  1109.                 return $this->last_result;
  1110.             }
  1111.         }
  1112.     }
  1113.  
  1114.     /**
  1115.      * Executes the given SQL query and returns a multi-dimensional array
  1116.      *
  1117.      * @param string $sql The query string should not end with a semicolon
  1118.      * @param integer $resultType (Optional) The type of array
  1119.      *                Values can be: MYSQL_ASSOC, MYSQL_NUM, MYSQL_BOTH
  1120.      * @return array A multi-dimensional array containing all the data
  1121.      *               returned from the query or FALSE on all errors
  1122.      */
  1123.     public function QueryArray($sql, $resultType = MYSQL_BOTH) {
  1124.         $this->Query($sql);
  1125.         if (! $this->Error()) {
  1126.             return $this->RecordsArray($resultType);
  1127.         } else {
  1128.             return false;
  1129.         }
  1130.     }
  1131.  
  1132.     /**
  1133.      * Executes the given SQL query and returns only one (the first) row
  1134.      *
  1135.      * @param string $sql The query string should not end with a semicolon
  1136.      * @return object PHP resource object containing the first row or
  1137.      *                FALSE if no row is returned from the query
  1138.      */
  1139.     public function QuerySingleRow($sql) {
  1140.         $this->Query($sql);
  1141.         if ($this->RowCount() > 0) {
  1142.             return $this->Row();
  1143.         } else {
  1144.             return false;
  1145.         }
  1146.     }
  1147.  
  1148.     /**
  1149.      * Executes the given SQL query and returns the first row as an array
  1150.      *
  1151.      * @param string $sql The query string should not end with a semicolon
  1152.      * @param integer $resultType (Optional) The type of array
  1153.      *                Values can be: MYSQL_ASSOC, MYSQL_NUM, MYSQL_BOTH
  1154.      * @return array An array containing the first row or FALSE if no row
  1155.      *               is returned from the query
  1156.      */
  1157.     public function QuerySingleRowArray($sql, $resultType = MYSQL_BOTH) {
  1158.         $this->Query($sql);
  1159.         if ($this->RowCount() > 0) {
  1160.             return $this->RowArray(null, $resultType);
  1161.         } else {
  1162.             return false;
  1163.         }
  1164.     }
  1165.  
  1166.     /**
  1167.      * Executes a query and returns a single value. If more than one row
  1168.      * is returned, only the first value in the first column is returned.
  1169.      *
  1170.      * @param string $sql The query string should not end with a semicolon
  1171.      * @return mixed The value returned or FALSE if no value
  1172.      */
  1173.     public function QuerySingleValue($sql) {
  1174.         $this->Query($sql);
  1175.         if ($this->RowCount() > 0 && $this->GetColumnCount() > 0) {
  1176.             $row = $this->RowArray(null, MYSQL_NUM);
  1177.             return $row[0];
  1178.         } else {
  1179.             return false;
  1180.         }
  1181.     }
  1182.  
  1183.     /**
  1184.      * Executes the given SQL query, measures it, and saves the total duration
  1185.      * in microseconds
  1186.      *
  1187.      * @param string $sql The query string should not end with a semicolon
  1188.      * @return object PHP 'mysql result' resource object containing the records
  1189.      *                on SELECT, SHOW, DESCRIBE or EXPLAIN queries and returns
  1190.      *                TRUE or FALSE for all others i.e. UPDATE, DELETE, DROP
  1191.      */
  1192.     public function QueryTimed($sql) {
  1193.         $this->TimerStart();
  1194.         $result = $this->Query($sql);
  1195.         $this->TimerStop();
  1196.         return $result;
  1197.     }
  1198.  
  1199.     /**
  1200.      * Returns the records from the last query
  1201.      *
  1202.      * @return object PHP 'mysql result' resource object containing the records
  1203.      *                for the last query executed
  1204.      */
  1205.     public function Records() {
  1206.         return $this->last_result;
  1207.     }
  1208.  
  1209.     /**
  1210.      * Returns all records from last query and returns contents as array
  1211.      * or FALSE on error
  1212.      *
  1213.      * @param integer $resultType (Optional) The type of array
  1214.      *                Values can be: MYSQL_ASSOC, MYSQL_NUM, MYSQL_BOTH
  1215.      * @return Records in array form
  1216.      */
  1217.     public function RecordsArray($resultType = MYSQL_BOTH) {
  1218.         $this->ResetError();
  1219.         if ($this->last_result) {
  1220.             if (! mysql_data_seek($this->last_result, 0)) {
  1221.                 $this->SetError();
  1222.                 return false;
  1223.             } else {
  1224.                 //while($member = mysql_fetch_object($this->last_result)){
  1225.                 while ($member = mysql_fetch_array($this->last_result, $resultType)){
  1226.                     $members[] = $member;
  1227.                 }
  1228.                 mysql_data_seek($this->last_result, 0);
  1229.                 $this->active_row = 0;
  1230.                 return $members;
  1231.             }
  1232.         } else {
  1233.             $this->active_row = -1;
  1234.             $this->SetError("No query results exist", -1);
  1235.             return false;
  1236.         }
  1237.     }
  1238.  
  1239.     /**
  1240.      * Frees memory used by the query results and returns the function result
  1241.      *
  1242.      * @return boolean Returns TRUE on success or FALSE on failure
  1243.      */
  1244.     public function Release() {
  1245.         $this->ResetError();
  1246.         if (! $this->last_result) {
  1247.             $success = true;
  1248.         } else {
  1249.             $success = @mysql_free_result($this->last_result);
  1250.             if (! $success) $this->SetError();
  1251.         }
  1252.         return $success;
  1253.     }
  1254.  
  1255.     /**
  1256.      * Clears the internal variables from any error information
  1257.      *
  1258.      */
  1259.     private function ResetError() {
  1260.         $this->error_desc = '';
  1261.         $this->error_number = 0;
  1262.     }
  1263.  
  1264.     /**
  1265.      * Reads the current row and returns contents as a
  1266.      * PHP object or returns false on error
  1267.      *
  1268.      * @param integer $optional_row_number (Optional) Use to specify a row
  1269.      * @return object PHP object or FALSE on error
  1270.      */
  1271.     public function Row($optional_row_number = null) {
  1272.         $this->ResetError();
  1273.         if (! $this->last_result) {
  1274.             $this->SetError("No query results exist", -1);
  1275.             return false;
  1276.         } elseif ($optional_row_number === null) {
  1277.             if (($this->active_row) > $this->RowCount()) {
  1278.                 $this->SetError("Cannot read past the end of the records", -1);
  1279.                 return false;
  1280.             } else {
  1281.                 $this->active_row++;
  1282.             }
  1283.         } else {
  1284.             if ($optional_row_number >= $this->RowCount()) {
  1285.                 $this->SetError("Row number is greater than the total number of rows", -1);
  1286.                 return false;
  1287.             } else {
  1288.                 $this->active_row = $optional_row_number;
  1289.                 $this->Seek($optional_row_number);
  1290.             }
  1291.         }
  1292.         $row = mysql_fetch_object($this->last_result);
  1293.         if (! $row) {
  1294.             $this->SetError();
  1295.             return false;
  1296.         } else {
  1297.             return $row;
  1298.         }
  1299.     }
  1300.  
  1301.     /**
  1302.      * Reads the current row and returns contents as an
  1303.      * array or returns false on error
  1304.      *
  1305.      * @param integer $optional_row_number (Optional) Use to specify a row
  1306.      * @param integer $resultType (Optional) The type of array
  1307.      *                Values can be: MYSQL_ASSOC, MYSQL_NUM, MYSQL_BOTH
  1308.      * @return array Array that corresponds to fetched row or FALSE if no rows
  1309.      */
  1310.     public function RowArray($optional_row_number = null, $resultType = MYSQL_BOTH) {
  1311.         $this->ResetError();
  1312.         if (! $this->last_result) {
  1313.             $this->SetError("No query results exist", -1);
  1314.             return false;
  1315.         } elseif ($optional_row_number === null) {
  1316.             if (($this->active_row) > $this->RowCount()) {
  1317.                 $this->SetError("Cannot read past the end of the records", -1);
  1318.                 return false;
  1319.             } else {
  1320.                 $this->active_row++;
  1321.             }
  1322.         } else {
  1323.             if ($optional_row_number >= $this->RowCount()) {
  1324.                 $this->SetError("Row number is greater than the total number of rows", -1);
  1325.                 return false;
  1326.             } else {
  1327.                 $this->active_row = $optional_row_number;
  1328.                 $this->Seek($optional_row_number);
  1329.             }
  1330.         }
  1331.         $row = mysql_fetch_array($this->last_result, $resultType);
  1332.         if (! $row) {
  1333.             $this->SetError();
  1334.             return false;
  1335.         } else {
  1336.             return $row;
  1337.         }
  1338.     }
  1339.  
  1340.     /**
  1341.      * Returns the last query row count
  1342.      *
  1343.      * @return integer Row count or FALSE on error
  1344.      */
  1345.     public function RowCount() {
  1346.         $this->ResetError();
  1347.         if (! $this->IsConnected()) {
  1348.             $this->SetError("No connection", -1);
  1349.             return false;
  1350.         } elseif (! $this->last_result) {
  1351.             $this->SetError("No query results exist", -1);
  1352.             return false;
  1353.         } else {
  1354.             $result = @mysql_num_rows($this->last_result);
  1355.             if (! $result) {
  1356.                 $this->SetError();
  1357.                 return false;
  1358.             } else {
  1359.                 return $result;
  1360.             }
  1361.         }
  1362.     }
  1363.  
  1364.     /**
  1365.      * Sets the internal database pointer to the
  1366.      * specified row number and returns the result
  1367.      *
  1368.      * @param integer $row_number Row number
  1369.      * @return object Fetched row as PHP object
  1370.      */
  1371.     public function Seek($row_number) {
  1372.         $this->ResetError();
  1373.         $row_count = $this->RowCount();
  1374.         if (! $row_count) {
  1375.             return false;
  1376.         } elseif ($row_number >= $row_count) {
  1377.             $this->SetError("Seek parameter is greater than the total number of rows", -1);
  1378.             return false;
  1379.         } else {
  1380.             $this->active_row = $row_number;
  1381.             $result = mysql_data_seek($this->last_result, $row_number);
  1382.             if (! $result) {
  1383.                 $this->SetError();
  1384.                 return false;
  1385.             } else {
  1386.                 $record = mysql_fetch_row($this->last_result);
  1387.                 if (! $record) {
  1388.                     $this->SetError();
  1389.                     return false;
  1390.                 } else {
  1391.                     // Go back to the record after grabbing it
  1392.                     mysql_data_seek($this->last_result, $row_number);
  1393.                     return $record;
  1394.                 }
  1395.             }
  1396.         }
  1397.     }
  1398.  
  1399.     /**
  1400.      * Returns the current cursor row location
  1401.      *
  1402.      * @return integer Current row number
  1403.      */
  1404.     public function SeekPosition() {
  1405.         return $this->active_row;
  1406.     }
  1407.  
  1408.     /**
  1409.      * Selects a different database and character set
  1410.      *
  1411.      * @param string $database Database name
  1412.      * @param string $charset (Optional) Character set (i.e. utf8)
  1413.      * @return boolean Returns TRUE on success or FALSE on error
  1414.      */
  1415.     public function SelectDatabase($database, $charset = "") {
  1416.         $return_value = true;
  1417.         if (! $charset) $charset = $this->db_charset;
  1418.         $this->ResetError();
  1419.         if (! (mysql_select_db($database))) {
  1420.             $this->SetError();
  1421.             $return_value = false;
  1422.         } else {
  1423.             if ((strlen($charset) > 0)) {
  1424.                 if (! (mysql_query("SET CHARACTER SET '{$charset}'", $this->mysql_link))) {
  1425.                     $this->SetError();
  1426.                     $return_value = false;
  1427.                 }
  1428.             }
  1429.         }
  1430.         return $return_value;
  1431.     }
  1432.  
  1433.     /**
  1434.      * Gets rows in a table based on a WHERE filter
  1435.      *
  1436.      * @param string $tableName The name of the table
  1437.      * @param array $whereArray (Optional) An associative array containing the
  1438.      *                          column names as keys and values as data. The
  1439.      *                          values must be SQL ready (i.e. quotes around
  1440.      *                          strings, formatted dates, ect)
  1441.      * @param array/string $columns (Optional) The column or list of columns to select
  1442.      * @param array/string $sortColumns (Optional) Column or list of columns to sort by
  1443.      * @param boolean $sortAscending (Optional) TRUE for ascending; FALSE for descending
  1444.      *                               This only works if $sortColumns are specified
  1445.      * @param integer/string $limit (Optional) The limit of rows to return
  1446.      * @return boolean Returns records on success or FALSE on error
  1447.      */
  1448.     public function SelectRows($tableName, $whereArray = null, $columns = null,
  1449.                                $sortColumns = null, $sortAscending = true,
  1450.                                $limit = null) {
  1451.         $this->ResetError();
  1452.         if (! $this->IsConnected()) {
  1453.             $this->SetError("No connection");
  1454.             return false;
  1455.         } else {
  1456.             $sql = self::BuildSQLSelect($tableName, $whereArray,
  1457.                     $columns, $sortColumns, $sortAscending, $limit);
  1458.             // Execute the UPDATE
  1459.             if (! $this->Query($sql)) {
  1460.                 return $this->last_result;
  1461.             } else {
  1462.                 return true;
  1463.             }
  1464.         }
  1465.     }
  1466.  
  1467.     /**
  1468.      * Retrieves all rows in a specified table
  1469.      *
  1470.      * @param string $tableName The name of the table
  1471.      * @return boolean Returns records on success or FALSE on error
  1472.      */
  1473.     public function SelectTable($tableName) {
  1474.         return $this->SelectRows($tableName);
  1475.     }
  1476.  
  1477.     /**
  1478.      * Sets the local variables with the last error information
  1479.      *
  1480.      * @param string $errorMessage The error description
  1481.      * @param integer $errorNumber The error number
  1482.      */
  1483.     private function SetError($errorMessage = "", $errorNumber = 0) {
  1484.         try {
  1485.             if (strlen($errorMessage) > 0) {
  1486.                 $this->error_desc = $errorMessage;
  1487.             } else {
  1488.                 if ($this->IsConnected()) {
  1489.                     $this->error_desc = mysql_error($this->mysql_link);
  1490.                 } else {
  1491.                     $this->error_desc = mysql_error();
  1492.                 }
  1493.             }
  1494.             if ($errorNumber <> 0) {
  1495.                 $this->error_number = $errorNumber;
  1496.             } else {
  1497.                 if ($this->IsConnected()) {
  1498.                     $this->error_number = @mysql_errno($this->mysql_link);
  1499.                 } else {
  1500.                     $this->error_number = @mysql_errno();
  1501.                 }
  1502.             }
  1503.         } catch(Exception $e) {
  1504.             $this->error_desc = $e->getMessage();
  1505.             $this->error_number = -999;
  1506.         }
  1507.         if ($this->ThrowExceptions) {
  1508.             if (isset($this->error_desc) && $this->error_desc != NULL) {
  1509.                 throw new Exception($this->error_desc . ' (' . __LINE__ . ')');
  1510.             }
  1511.         }
  1512.     }
  1513.  
  1514.     /**
  1515.      * [STATIC] Converts a boolean into a formatted TRUE or FALSE value of choice
  1516.      *
  1517.      * @param mixed $value value to analyze for TRUE or FALSE
  1518.      * @param mixed $trueValue value to use if TRUE
  1519.      * @param mixed $falseValue value to use if FALSE
  1520.      * @param string $datatype Use SQLVALUE constants or the strings:
  1521.      *                          string, text, varchar, char, boolean, bool,
  1522.      *                          Y-N, T-F, bit, date, datetime, time, integer,
  1523.      *                          int, number, double, float
  1524.      * @return string SQL formatted value of the specified data type
  1525.      */
  1526.     static public function SQLBooleanValue($value, $trueValue, $falseValue, $datatype = self::SQLVALUE_TEXT) {
  1527.         if (self::GetBooleanValue($value)) {
  1528.            $return_value = self::SQLValue($trueValue, $datatype);
  1529.         } else {
  1530.            $return_value = self::SQLValue($falseValue, $datatype);
  1531.         }
  1532.         return $return_value;
  1533.     }
  1534.  
  1535.     /**
  1536.      * [STATIC] Returns string suitable for SQL
  1537.      *
  1538.      * @param string $value
  1539.      * @return string SQL formatted value
  1540.      */
  1541.     static public function SQLFix($value) {
  1542.         return @addslashes($value);
  1543.     }
  1544.  
  1545.     /**
  1546.      * [STATIC] Returns MySQL string as normal string
  1547.      *
  1548.      * @param string $value
  1549.      * @return string
  1550.      */
  1551.     static public function SQLUnfix($value) {
  1552.         return @stripslashes($value);
  1553.     }
  1554.  
  1555.     /**
  1556.      * [STATIC] Formats any value into a string suitable for SQL statements
  1557.      * (NOTE: Also supports data types returned from the gettype function)
  1558.      *
  1559.      * @param mixed $value Any value of any type to be formatted to SQL
  1560.      * @param string $datatype Use SQLVALUE constants or the strings:
  1561.      *                          string, text, varchar, char, boolean, bool,
  1562.      *                          Y-N, T-F, bit, date, datetime, time, integer,
  1563.      *                          int, number, double, float
  1564.      * @return string
  1565.      */
  1566.     static public function SQLValue($value, $datatype = self::SQLVALUE_TEXT) {
  1567.         $return_value = "";
  1568.  
  1569.         switch (strtolower(trim($datatype))) {
  1570.             case "text":
  1571.             case "string":
  1572.             case "varchar":
  1573.             case "char":
  1574.                 if (strlen($value) == 0) {
  1575.                     $return_value = "NULL";
  1576.                 } else {
  1577.                     if (get_magic_quotes_gpc()) {
  1578.                         $value = stripslashes($value);
  1579.                     }
  1580.                     $return_value = "'" . str_replace("'", "''", $value) . "'";
  1581.                 }
  1582.                 break;
  1583.             case "number":
  1584.             case "integer":
  1585.             case "int":
  1586.             case "double":
  1587.             case "float":
  1588.                 if (is_numeric($value)) {
  1589.                     $return_value = $value;
  1590.                 } else {
  1591.                     $return_value = "NULL";
  1592.                 }
  1593.                 break;
  1594.             case "boolean":  //boolean to use this with a bit field
  1595.             case "bool":
  1596.             case "bit":
  1597.                 if (self::GetBooleanValue($value)) {
  1598.                    $return_value = "1";
  1599.                 } else {
  1600.                    $return_value = "0";
  1601.                 }
  1602.                 break;
  1603.             case "y-n":  //boolean to use this with a char(1) field
  1604.                 if (self::GetBooleanValue($value)) {
  1605.                     $return_value = "'Y'";
  1606.                 } else {
  1607.                     $return_value = "'N'";
  1608.                 }
  1609.                 break;
  1610.             case "t-f":  //boolean to use this with a char(1) field
  1611.                 if (self::GetBooleanValue($value)) {
  1612.                     $return_value = "'T'";
  1613.                 } else {
  1614.                     $return_value = "'F'";
  1615.                 }
  1616.                 break;
  1617.             case "date":
  1618.                 if (self::IsDate($value)) {
  1619.                     $return_value = "'" . date('Y-m-d', strtotime($value)) . "'";
  1620.                 } else {
  1621.                     $return_value = "NULL";
  1622.                 }
  1623.                 break;
  1624.             case "datetime":
  1625.                 if (self::IsDate($value)) {
  1626.                     $return_value = "'" . date('Y-m-d H:i:s', strtotime($value)) . "'";
  1627.                 } else {
  1628.                     $return_value = "NULL";
  1629.                 }
  1630.                 break;
  1631.             case "time":
  1632.                 if (self::IsDate($value)) {
  1633.                     $return_value = "'" . date('H:i:s', strtotime($value)) . "'";
  1634.                 } else {
  1635.                     $return_value = "NULL";
  1636.                 }
  1637.                 break;
  1638.             default:
  1639.                 exit("ERROR: Invalid data type specified in SQLValue method");
  1640.         }
  1641.         return $return_value;
  1642.     }
  1643.  
  1644.     /**
  1645.      * Returns last measured duration (time between TimerStart and TimerStop)
  1646.      *
  1647.      * @param integer $decimals (Optional) The number of decimal places to show
  1648.      * @return Float Microseconds elapsed
  1649.      */
  1650.     public function TimerDuration($decimals = 4) {
  1651.         return number_format($this->time_diff, $decimals);
  1652.     }
  1653.  
  1654.     /**
  1655.      * Starts time measurement (in microseconds)
  1656.      *
  1657.      */
  1658.     public function TimerStart() {
  1659.         $parts = explode(" ", microtime());
  1660.         $this->time_diff = 0;
  1661.         $this->time_start = $parts[1].substr($parts[0],1);
  1662.     }
  1663.  
  1664.     /**
  1665.      * Stops time measurement (in microseconds)
  1666.      *
  1667.      */
  1668.     public function TimerStop() {
  1669.         $parts  = explode(" ", microtime());
  1670.         $time_stop = $parts[1].substr($parts[0],1);
  1671.         $this->time_diff  = ($time_stop - $this->time_start);
  1672.         $this->time_start = 0;
  1673.     }
  1674.  
  1675.     /**
  1676.      * Starts a transaction
  1677.      *
  1678.      * @return boolean Returns TRUE on success or FALSE on error
  1679.      */
  1680.     public function TransactionBegin() {
  1681.         $this->ResetError();
  1682.         if (! $this->IsConnected()) {
  1683.             $this->SetError("No connection");
  1684.             return false;
  1685.         } else {
  1686.             if (! $this->in_transaction) {
  1687.                 if (! mysql_query("START TRANSACTION", $this->mysql_link)) {
  1688.                     $this->SetError();
  1689.                     return false;
  1690.                 } else {
  1691.                     $this->in_transaction = true;
  1692.                     return true;
  1693.                 }
  1694.             } else {
  1695.                 $this->SetError("Already in transaction", -1);
  1696.                 return false;
  1697.             }
  1698.         }
  1699.     }
  1700.  
  1701.     /**
  1702.      * Ends a transaction and commits the queries
  1703.      *
  1704.      * @return boolean Returns TRUE on success or FALSE on error
  1705.      */
  1706.     public function TransactionEnd() {
  1707.         $this->ResetError();
  1708.         if (! $this->IsConnected()) {
  1709.             $this->SetError("No connection");
  1710.             return false;
  1711.         } else {
  1712.             if ($this->in_transaction) {
  1713.                 if (! mysql_query("COMMIT", $this->mysql_link)) {
  1714.                     // $this->TransactionRollback();
  1715.                     $this->SetError();
  1716.                     return false;
  1717.                 } else {
  1718.                     $this->in_transaction = false;
  1719.                     return true;
  1720.                 }
  1721.             } else {
  1722.                 $this->SetError("Not in a transaction", -1);
  1723.                 return false;
  1724.             }
  1725.         }
  1726.     }
  1727.  
  1728.     /**
  1729.      * Rolls the transaction back
  1730.      *
  1731.      * @return boolean Returns TRUE on success or FALSE on failure
  1732.      */
  1733.     public function TransactionRollback() {
  1734.         $this->ResetError();
  1735.         if (! $this->IsConnected()) {
  1736.             $this->SetError("No connection");
  1737.             return false;
  1738.         } else {
  1739.             if(! mysql_query("ROLLBACK", $this->mysql_link)) {
  1740.                 $this->SetError("Could not rollback transaction");
  1741.                 return false;
  1742.             } else {
  1743.                 $this->in_transaction = false;
  1744.                 return true;
  1745.             }
  1746.         }
  1747.     }
  1748.  
  1749.     /**
  1750.      * Truncates a table removing all data
  1751.      *
  1752.      * @param string $tableName The name of the table
  1753.      * @return boolean Returns TRUE on success or FALSE on error
  1754.      */
  1755.     public function TruncateTable($tableName) {
  1756.         $this->ResetError();
  1757.         if (! $this->IsConnected()) {
  1758.             $this->SetError("No connection");
  1759.             return false;
  1760.         } else {
  1761.             $sql = "TRUNCATE TABLE `" . $tableName . "`";
  1762.             if (! $this->Query($sql)) {
  1763.                 return false;
  1764.             } else {
  1765.                 return true;
  1766.             }
  1767.         }
  1768.     }
  1769.  
  1770.     /**
  1771.      * Updates rows in a table based on a WHERE filter
  1772.      * (can be just one or many rows based on the filter)
  1773.      *
  1774.      * @param string $tableName The name of the table
  1775.      * @param array $valuesArray An associative array containing the column
  1776.      *                            names as keys and values as data. The values
  1777.      *                            must be SQL ready (i.e. quotes around
  1778.      *                            strings, formatted dates, ect)
  1779.      * @param array $whereArray (Optional) An associative array containing the
  1780.      *                           column names as keys and values as data. The
  1781.      *                           values must be SQL ready (i.e. quotes around
  1782.      *                           strings, formatted dates, ect). If not specified
  1783.      *                           then all values in the table are updated.
  1784.      * @return boolean Returns TRUE on success or FALSE on error
  1785.      */
  1786.     public function UpdateRows($tableName, $valuesArray, $whereArray = null) {
  1787.         $this->ResetError();
  1788.         if (! $this->IsConnected()) {
  1789.             $this->SetError("No connection");
  1790.             return false;
  1791.         } else {
  1792.             $sql = self::BuildSQLUpdate($tableName, $valuesArray, $whereArray);
  1793.             // Execute the UPDATE
  1794.             if (! $this->Query($sql)) {
  1795.                 return false;
  1796.             } else {
  1797.                 return true;
  1798.             }
  1799.         }
  1800.     }
  1801.    
  1802.     public function SetPrefix($prefix = NULL)
  1803.     {  
  1804.         if ($prefix !== null)   $this->table_prefix = $prefix;
  1805.         return true;
  1806.     }
  1807. }
  1808. ?>
Advertisement
Add Comment
Please, Sign In to add comment