row() to be able to return a single field value * 2004-04-09 - Added ReplaceDelayed * 2004-03-18 - Added InsertDelayed function * - Added ValidLink function * - Added $use_persistent property (Default = true) * - Added $autostripslashes property (Default = false) */ class DBTable { var $host; var $user; var $password; var $database; var $link; var $result; var $sql; var $use_persistent; var $autostripslashes; var $error_level; var $lasterror; var $shadowdb; //None of the queuries execute - the actual SQL are just logged in an array! var $sqllog; var $logsql; //Must we log all SQL calls? var $boolvalue; //Default boolean values to use for true/false in parameterized SQL statements var $params; //SQL Parameters /* * DBTable * This is the default constructor of the class. It sets all * te neccesary variables. */ function DBTable() { $this->use_persistent = true; $this->autostripslashes = false; $this->error_level = 4; //Default error level - show SQL errors $this->shadowdb = false; $this->sqllog = array(); $this->logsql = false; $this->delayedconnect = false; $this->host = 'localhost'; $this->user = 'root'; $this->password = '3.Wrvnn'; $this->database = 'mysql'; unset($link); unset($sql); unset($result); $this->boolvalue = array(false => "0", True => "1"); $this->ClearParams(); } /* * DoError * It traces an SQL error and outputs status, error number and error string * to the user. * * Params * $sql string Empties the $sql variable. */ function DoError($sql = "") { global $SCRIPT_FILENAME, $QUERY_STRING, $REQUEST_METHOD, $HTTP_USER_AGENT, $HTTP_REFERER; $SQL_ERR = mysql_errno(); $SQL_ERRSTR = mysql_error(); switch($this->error_level) { case 4 : //Special debugging - email errors $err = array(); $err["code"] = $SQL_ERR; $err["msg"] = $SQL_ERRSTR; $err["sql"] = $sql; $this->lasterror = $err; $body = "code=$SQL_ERR\nmsg=$SQL_ERRSTR\nSQL=$sql\n"; $body .= "date=".Date("Y-m-d H:i:s")."\n"; $body .= "script=".$SCRIPT_FILENAME."\n"; $body .= "query_str=".$QUERY_STRING."\n"; $body .= "method=".$REQUEST_METHOD."\n"; $body .= "agent=".$HTTP_USER_AGENT."\n"; $body .= "referer=".$HTTP_REFERER."\n"; $body .= "POST=".Array2Params($_POST)."\n"; $body .= "\n"; if(($SQL_ERR==1213) || ($SQL_ERR==1205)) { $this->open("SHOW INNODB STATUS"); $row = $this->row(); $body .= "INNODB STATUS\n".$row[0]."\n"; } //if ( get_cfg_var ( 'DEV-SERVER') ) if(true) { echo "
$body

"; //phpinfo(); } else { mail("clickbutt@gcs.co.za","[SQL] Error $SQL_ERR",$body); } echo "Database error occurred. Please try again or contact support at http://spacialaudio.com/support/support.html"; Exit; break; case 3 : //do not display any errors, just store the error codes $err = array(); $err["code"] = $SQL_ERR; $err["msg"] = $SQL_ERRSTR; $err["sql"] = $sql; $this->lasterror = $err; break; //Display error and do not exit case 2 : echo "status=err
"; echo "SQL error=$SQL_ERR
"; echo "SQL error string=$SQL_ERRSTR
"; echo "SQL=
".htmlentities($sql)."

"; break; //Display error and immediately exit case 1 : ; default : echo "status=err
"; echo "SQL error=$SQL_ERR
"; echo "SQL error string=$SQL_ERRSTR
"; echo "SQL=
".htmlentities($sql)."

"; Exit; break; } } //Unconditionally aborts script. This is usually only done if a logical programming error is made //For example, trying to read a result set while in shadow mode function DoAbort($msg) { echo "Error:
"; echo "message=$msg
"; Exit; } /* Stores SQL queries in internal sqllog array */ function DoLogSQL($sql) { $this->sqllog[] = $sql; } /* * StripSlashes * Strips all the slashes from data received * * Params * $data mixed The data received * Return mixed The new data without any slashes in it */ function StripSlashes($data) { if($this->autostripslashes == true) { return $this->StripArray($data); } else return $data; } /* * StripArray * Takes an array and strips it from slashes * * Params $arr array the array needing to be stripped Returns array Returns the array that is stripped of its slashes */ function StripArray($arr) { if(!is_array($arr)) return stripslashes($arr); else foreach($arr as $key => $val) { if(is_array($val)) $arr["$key"] = $this->StripArray($val); else $arr["$key"] = stripslashes($val); } return $arr; } function FindSQLParams(&$sql) { $escaped = false; $escapechars = explode(",","\",',`"); $res = ""; $cnt = 0; for($i=0;$i0) && (substr($sql,$i-1,1)=="\\"))) $escaped = !$escaped; if($char==":" && !$escaped) { //Add parameterized string $res .= ":p$cnt:"; $cnt++; //Find the end of the parameter for($c=$i+1;$c='a' && $char2<='z') || ($char2>='0' && $char2<='9') || ($char2=="_"))) break; $i++; } } else $res .= $char; } $sql = $res; return $cnt; } //Returns a unix timestamp. //If $val is a string, it is converted to a timestamp using the strtotime function function AsTimeStamp($val) { $stamp = $val; if(!is_numeric($stamp)) $stamp = strtotime($stamp); return $stamp; } //Checks SQL string and assign parameters to string. function FillSQLParams($conn,$sql,$params) { if(is_array($params) && (count($params)>0)) { $cnt = $this->FindSQLParams($sql); $c=0; foreach($params as $param) { if($param["type"]=="auto") $param["type"] = gettype($param["value"]); switch(strtolower($param["type"])) { //Valid auto-detect types case "boolean" : $val = $this->boolvalue[$param["value"]]; break; case "integer" : $val = $param["value"]; settype($val,"integer"); break; case "double" : $val = $param["value"]; settype($val,"double"); break; case "string" : $val = "'".mysqli_real_escape_string($conn, $param["value"])."'"; break; case "NULL" : $val = 'NULL'; break; //Custom types case "date" : $stamp = $this->AsTimeStamp($param["value"]); $val = Date("'Y-m-d'",$stamp); break; case "time" : $stamp = $this->AsTimeStamp($param["value"]); $val = Date("'H:i:s'",$stamp); break; case "datetime" : $stamp = $this->AsTimeStamp($param["value"]); $val = Date("'Y-m-d H:i:s'",$stamp); break; case "statement" : //WARNING: Use this one with caution - its an open hole for SQL injection! $val = $param["value"]; break; //Invalid auto-types case "array" : case "object" : case "resource" : case "unknown type" : case "user function" : $this->DoAbort("Parameter type not supported ($param[type])."); break; }//switch $sql = str_replace(":p$c:",$val,$sql); $c++; }//foreach }//if return $sql; } function AddParam($val, $type = "auto") { $param["value"] = $val; $param["type"] = $type; $this->params[] = $param; } function AddParams($values, $type = "auto") { foreach($values as $val) $this->AddParam($val,$type); } function SetParams() { $param_list = func_get_args(); $this->AddParams($param_list); } function ClearParams() { $this->params = array(); } function AddStr($val){ $this->AddParam($val,"string"); } function AddString($val){ $this->AddParam($val,"string"); } function AddInt($val){ $this->AddParam($val,"integer"); } function AddInteger($val){ $this->AddParam($val,"integer"); } function AddFloat($val){ $this->AddParam($val,"double"); } function AddDouble($val){ $this->AddParam($val,"double"); } function AddDate($val){ $this->AddParam($val,"date"); } function AddTime($val){ $this->AddParam($val,"time"); } function AddDateTime($val){ $this->AddParam($val,"datetime"); } function AddTimeStamp($val){ $this->AddParam($val,"datetime"); } function AddBool($val){ $this->AddParam($val,"boolean"); } function AddStatement($val){ $this->AddParam($val,"statement"); } function AddNull(){ $this->AddParam(NULL,"statement"); } /* * connect * Connects to database using connection details. * Note: If you are not running on default port, append port to host, i.e. myip:port * * Params * $host string Takes the host as a parameter e.g localhost $user string The username to use for that SQL server $password string The corresponding password $database string The database name */ function connect($host = "", $user = "", $password = "", $database = "") { if(!empty($host)) $this->host = $host; if(!empty($user)) $this->user = $user; if(!empty($password)) $this->password = $password; if(!empty($database)) $this->database = $database; if(($this->logsql) || ($this->shadowdb)) $this->DoLogSQL("USE ".$this->database); //Connect only if not ShadowDB, and not when delayed connects if(!$this->shadowdb && !$this->delayedconnect) $this->forceconnect(); } /* * connectdb * Connects to the database * * Params * $login array Array containing the host, username and password. $database string String containging the database name. (optional - if $login["database"] is valid) */ function connectdb($login, $database = '') { if(empty($database)) $database = $login["database"]; $this->connect($login["host"],$login["username"],$login["password"],$database); } function forceconnect() { if($this->use_persistent) //$this->link = mysql_pconnect($this->host, $this->user, $this->password); $this->link = mysqli_connect($this->host, $this->user, $this->password); else $this->link = mysqli_connect($this->host, $this->user, $this->password); if(!empty($this->database)) mysqli_select_db($this->link, $this->database); return $this->link; } /* * ValidLink * Checks to see if the link/connection to the database is valid * * Params * Return bool returns the true if it is a valid link */ function ValidLink() { if($this->shadowdb) $this->DoAbort("Operation not allowed under Shadow mode"); if(!$this->delayedconnect) $this->forceconnect(); return ($this->link != FALSE); } /* * query * Executes an SQL query and saves the result set * Connects to database if needed * * * Params * $sql string A string containg the SQL query * Return resultset Returns the results from the query */ function query($sql, $limit = 0, $skip = 0) { //If we have filled parameters, use them // if(count($this->params)>0) { $sql = $this->FillSQLParams($sql,$this->params); $this->ClearParams(); } //Connect if needed if(!$this->shadowdb && !$this->ValidLink()) $this->forceconnect(); //If we have filled parameters, use them if(count($this->params)>0) { $sql = $this->FillSQLParams($this->link,$sql,$this->params); $this->ClearParams(); } $skip = (int)$skip; $limit = (int)$limit; if($limit>0) { if($skip>0) $sql .= " LIMIT $skip,$limit"; else $sql .= " LIMIT $limit"; } $this->sql = $sql; //Log SQL if needed if(($this->logsql) || ($this->shadowdb)) $this->DoLogSQL($this->sql); if(!$this->shadowdb) { mysqli_select_db($this->link, $this->database); $this->result = mysqli_query($this->link, $sql) or $this->DoError($sql); return $this->result; } } /* * open * Executes a SQL query and returns the result * * Params * $sql string A string containg the SQL query * Return resultset Returns the results from the query */ function Open($sql, $limit = 0, $skip = 0) { //Additional arguments passed are used as SQL Parameters if(func_num_args()>3) { $param_list = func_get_args(); $this->AddParams(array_slice($param_list,3)); } return $this->query($sql, $limit, $skip); } function OpenEx($sql) { //Additional arguments passed are used as SQL Parameters if(func_num_args()>1) { $param_list = func_get_args(); $this->AddParams(array_slice($param_list,1)); } $this->open($sql); } /* * execsql * Executes a SQL query but does not save the results * * Params * $sql string A string containg the SQL query */ function execsql($sql) { //Additional arguments passed are used as SQL Parameters if(func_num_args()>1) { $param_list = func_get_args(); $this->AddParams(array_slice($param_list,1)); } //If we have filled parameters, use them if(count($this->params)>0) { $sql = $this->FillSQLParams($sql,$this->params); $this->ClearParams(); } //Connect if needed if(!$this->shadowdb && !$this->ValidLink()) $this->forceconnect(); $this->sql = $sql; //Log SQL if needed if(($this->logsql) || ($this->shadowdb)) $this->DoLogSQL($this->sql); if(!$this->shadowdb) { mysqli_select_db($this->link, $this->database); mysqli_query($this->link, $sql) or $this->DoError($sql); } } /* * next * Returns the next row in the resultset if there is any * * Return array The results in the next row of the resultset */ function next() { if($this->shadowdb) $this->DoAbort("Operation not allowed under Shadow mode"); return mysqli_fetch_array($this->result); } /* * getrow * gets the data of the next row in a resultset * * Params * Return array The results of the next row in the resultset */ function getrow() { return $this->next(); } /* * row * Gets a row from a record in the database * If a fieldname is supplied, only return the value of that field for the next/first row * * Params (ALL optional) * $fieldname string A string containg the name of a field in the table (Optional) * Return array Returns the next row from the selected record set, or the value of the field in the next row */ function row($fieldname = '') { $res = $this->next(); //Quick way to get complete record if(!empty($fieldname)) $res = $res[$fieldname]; return $res; } /* * getrows * gets all the rows from a selected record in a database * * Params * Return mixed All the rows of the selected record */ function getrows() { $data = array(); while ($row = $this->getrow()) $data[] = $row; return $data; } /* * rows * gets all the rows from a selected record in a database * * Params * Return mixed All the rows of the selected record */ function rows() { return $this->getrows(); } /* * insert * inserts data into a table of a selected database * * Params $table string The name of the table where the data needs to be inserted $data array An associative array containing the data to be inserted into the database Example: * $data = array(); * $data["fieldname"] = "FieldValue"; * $db->insert("MyTable",$data); */ function insert($table,$data) { $this->CreateSQLQuery($this->StripSlashes($data),$fields,$values,"INSERT"); $this->execsql("INSERT INTO $table ($fields) VALUES($values)"); } public function insertupdate($table, $insertdata, $updatedata) { $this->CreateSQLQuery($this->StripSlashes($insertdata),$fields,$values,"INSERT"); $this->CreateSQLQuery($this->StripSlashes($updatedata),$dummy,$updates,"UPDATE"); return $this->execsql("INSERT INTO $table ($fields) VALUES ($values) ON DUPLICATE KEY UPDATE $updates"); } /* * CreateSQLQuery * Creates an SQL query * * Params $form array The data to be entered into the database $fields mixed The specific names of the fields $values mixed The values of the forms to be entered $mode string The mode of the Query (update/delete) */ function CreateSQLQuery($form,&$fields,&$values,$mode) { //Set Database insert/update mode $fields = ""; $values = ""; reset($form); while (list($key, $val) = each($form)) { if ($key[0]!='_') $this->AddKey($key,$val,$fields,$values,$mode,"auto"); } } /* * AddKey * Adds a key to a record in the database * * Params $field string The field name $value mixed The values to be inserted $fields mixed The field names where the data must be inserted $values mixed The values to be inserted corresponding to the field names $DBmode string The type of operation on the DB (insert/update) $type string The data type corresponding to the fields */ function AddKey($field,$value,&$fields, &$values, $DBmode, $type = "string") { if ($type == "auto") { switch(strtoupper($value)) { case "NULL" : $type = "NULL"; break; case "NOW()" : $type = "FUNC"; break; case "CURDATE()" : $type = "FUNC"; break; case "CURTIME()" : $type = "FUNC"; break; case "UNIX_TIMESTAMP()" : $type = "FUNC"; break; default : $type = gettype($value); } if(substr(strtoupper($value), 0, 9) == "DATE_ADD(") $type = "FUNC"; if(substr(strtoupper($value), 0, 9) == "DATE_SUB(") $type = "FUNC"; } switch ($type) { case "FUNC" : case "NULL" : case "null" : case "double" : case "float" : case "integer" : $doStr = ""; break; case "string" : default : $value=addslashes($value); $doStr = "'"; } $DBmode = strtoupper($DBmode); if ($DBmode=="UPDATE") { if (!empty($values)) $values .= ","; $values .= $field . " = $doStr" . $value . "$doStr "; } else { if (!empty($fields)) $fields .= ","; if (!empty($values)) $values .= ","; $fields .= $field; $values .= "$doStr" . $value . "$doStr "; } } /* * insertdelayed * inserts data into the database but with a delayed query * * Params $table string The name of the table where the data needs to be inserted $data array An array containing the data to be inserted into the database */ function insertdelayed($table,$data) { global $commonpath; require_once("$commonpath/form.php"); CreateSQLQuery($this->StripSlashes($data),$fields,$values,"INSERT"); $this->execsql("INSERT DELAYED INTO $table ($fields) VALUES($values)"); } /* * replace * replaces data inside a certain record. * * Params $table string The name of the table where the data needs to be replaced $data array An array containing the data to be replaced within the database */ function replace($table,$data) { global $commonpath; require_once("$commonpath/form.php"); CreateSQLQuery($this->StripSlashes($data),$fields,$values,"INSERT"); $this->execsql("REPLACE INTO $table ($fields) VALUES($values)"); } /* * replacedelayed * replaces data inside a certain record but it is delayed. * * Params $table string The name of the table where the data needs to be replaced $data array An array containing the data to be replaced within the database */ function replacedelayed($table,$data) { global $commonpath; require_once("$commonpath/form.php"); CreateSQLQuery($this->StripSlashes($data),$fields,$values,"INSERT"); $this->execsql("REPLACE DELAYED INTO $table ($fields) VALUES($values)"); } /* * update * update data inside a certain record. * * Params $table string The name of the table where the data needs to be updated $data array An associative array containing the updated data $where string A string containg the where clause for the SQL query */ function update($table, $data, $where) { global $commonpath; require_once("$commonpath/form.php"); CreateSQLQuery($this->StripSlashes($data),$fields,$values,"UPDATE"); $this->execsql("UPDATE $table SET $values WHERE $where "); } /* * delete * deletes a certain record. * * Params $table string The name of the table to be deleted $where string A string containing the where clause for the SQL query (Excluding the WHERE keyword) */ function delete($table, $where) { $this->execsql("DELETE FROM $table WHERE $where "); } /* * inset_id * Retrieves the primary key (ID) from the last insert operation. * * Return The ID of the record */ function insert_id() { if($this->shadowdb) $this->DoAbort("Operation not allowed under Shadow mode"); return mysql_insert_id($this->link); } /* * recordcount * takes the results of a query and counts the number of rows. * * Returns int The number of rows or -1 if not applicable */ function recordcount() { if($this->shadowdb) $this->DoAbort("Operation not allowed under Shadow mode"); if ($this->result) { return mysqli_num_rows($this->result); } else { return -1; }; } /* * num_rows * does a recordcount * * Returns int The number of rows in the resultset */ function num_rows() { return $this->recordcount(); } /* * affected_rows * Returns the number of rows affected in a UPDATE or DELETE sql query. * * Returns int The number of effected rows */ function affected_rows() { if($this->shadowdb) $this->DoAbort("Operation not allowed under Shadow mode"); return mysql_affected_rows($this->link); } function NewTransaction() { $this->open("START TRANSACTION"); } function commit() { $this->execsql("COMMIT"); } function rollback() { $this->execsql("ROLLBACK"); } /* * GetEnumValues * gets all the enum values from a record row * * Params $table string The name of the table where the data exists $field array The name of the field where the data exists Returns array An array with the enumerated data */ FUNCTION GetEnumValues( $table, $field ) { if($this->shadowdb) $this->DoAbort("Operation not allowed under Shadow mode"); // Query Database for field structure $sql = "SHOW COLUMNS FROM $table LIKE '$field'"; $this->open( $sql ); // Get the data $data = $this->getrow(); if (( substr_count($data[1], "enum") > 0 ) or ( substr_count($data[1], "set") > 0 )) { // format Enum vars into an array return explode("','",preg_replace("/(enum|set)\('(.+?)'\)/","\\2",$data[1])); }; } /* * GetFieldNames * Returns an array containing all the fieldnames of the table * Params $table string The name of the table */ function GetFieldNames($table) { $fields = array(); $sql = "SHOW COLUMNS FROM $table "; $this->open($sql); while($row = $this->row()) $fields[] = $row[0]; return $fields; } /* * BatchExecute * Executes multiple SQL queries * Params $sql string SQL statements, seperated by ;\n (semi-colon followed by newline) */ function BatchExecute($sql) { $src = array(); //First remove all comments //Note: This also removes whitespace: Spaces, NewLines (\n) and ReturnLines (\r) $lines = explode("\n",$sql); foreach($lines as $line) if($line[0]!="#") $src[] = trim($line); $sql = implode("\n",$src); //Batch execute SQL $sql = explode(";\n",$sql); foreach($sql as $query) { $query = trim($query); if(!empty($query)) $this->open($query); } } /* * TableExists * Checks whether a table exists in the database * * Params $TableName string The name of the table to be checked Returns boolean Returns true if the table exists or false if does not exist */ function TableExists($TableName) { if($this->shadowdb) $this->DoAbort("Operation not allowed under Shadow mode"); $result = mysql_list_tables($this->database, $this->link); while ($row=mysql_fetch_array($result, MYSQL_NUM)) { if ($row[0] == $TableName) { $bRetVal = TRUE; break; }; }; mysql_free_result($result); return ($bRetVal); } /* * DatabaseExists * Checks whether a database exists in the MySQL server * * Params $DatabaseName string The name of the database to be checked Returns boolean Returns true if the database exists or false if does not exist */ function DatabaseExists($DatabaseName) { if($this->shadowdb) $this->DoAbort("Operation not allowed under Shadow mode"); $this->open("SHOW DATABASES LIKE '$DatabaseName' "); if($this->num_rows()>0) { $row = $this->row(); if ($row[0] == $DatabaseName) return true; } return false; } function HashTableName($table, $hashID, $max = 32) { $c = ($hashID % $max); $table = sprintf("%s%02d",$table,$c); return $table; } }; // end of class ?>