Advertisement
mpansaldi84

Ultimate MySQL Wrapper Class - Using MySQLi

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