"0", true => "1"); ///< Default boolean values to use for true/false in parameterized SQL statements public $name = ""; ///< The name of the parameter public $value = ""; ///< The value of the parameter public $type = ""; ///< The type of the parameter /*================================================================== SECTION: MAGIC methods ------------------------------------------------------------------*/ /** * TDBParam::__construct() * @brief The TDBParam constructor to set up the TDBParam object. * * @param TDBParams::$owner The TDBParams object * @param $value The value of the parameter * @param $name The name of the parameter * @param $type The type of the parameter **/ function __construct(TDBParams $owner, $value, $name = "", $type = "auto") { $this->owner = $owner; $this->set($value, $name, $type); } /** * TDBParam::AsTimeStamp() * @brief Returns a unix timestamp. * If $val is a string, it is converted to a timestamp using the strtotime function * @param mixed $val * @return a unix timestamp. **/ private function AsTimeStamp($val) { $stamp = $val; if(!is_numeric($stamp)) $stamp = strtotime($stamp); return $stamp; } /** * TDBParam::escape_string() * $brief Escape the string using the mysqli->escape_string * * @see TDB::escape_string() **/ private function escape_string($val) { return $this->owner->escape_string($val); } /*================================================================== SECTION: Core param methods ------------------------------------------------------------------*/ /** * TDBParam::set() * @brief Change the value, name and type of this object * * @param $value The value of the parameter * @param $name The name of the parameter * @param $type The type of the parameter * @return True **/ public function set($value, $name = "", $type = "auto") { $this->name = $name; $this->value = $value; $this->type = $type; return true; } /** * TDBParam::bindtype() * @brief Return the "Prepared query bind type" of the value * * @return The param type * @warning Blob type not implemented yet **/ public function bindtype() { if($this->type=="auto") $type = gettype($this->value); else $type = $this->type; switch(strtolower($type)) //Valid auto-detect types { case "integer" : $val = "i"; break; case "double" : $val = "d"; break; case "blob" : $val = "b"; break; //NOTE: Not yet implemented default : $val = "s"; break; } return $val; } /** * TDBParam::AsString() * @brief Convert parameter to SQL string that is "SQL-injection safe" * * @return The param type * @warning Use "Statement" with caution - its an open hole for SQL injection! **/ public function AsString() { if($this->type=="auto") $type = gettype($this->value); else $type = $this->type; switch(strtolower($type)) { //Valid auto-detect types case "boolean" : $val = $this->boolvalue[$this->value]; break; case "integer" : $val = $this->value; settype($val,"integer"); break; case "double" : $val = $this->value; settype($val,"double"); break; case "string" : //This is unfortunately a slight *hack* as the param //needs to be aware of the SQL connection to properly format the string $val = $this->escape_string($this->value); break; case "null" : $val = 'NULL'; break; //Custom types case "date" : $stamp = $this->AsTimeStamp($this->value); $val = Date("'Y-m-d'",$stamp); break; case "time" : $stamp = $this->AsTimeStamp($this->value); $val = Date("'H:i:s'",$stamp); break; case "datetime" : $stamp = $this->AsTimeStamp($this->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 = $this->value; break; case "function" : $func = $this->value["function"]; $param = $this->value["param"]; $val = $func."(".$param->AsString().")"; break; //Invalid auto-types case "array" : case "object" : case "resource" : case "unknown type" : case "user function" : default : throw new Exception("TDBParam.AsString: Parameter type not supported ($type)."); break; }//switch return $val; } } //TDBParam class //############################################################################## /** * TDBParams * @brief Class encapsulates a collection of values to be used within an SQL query * * @author SpacialDev CC * @version $Id: class.db.php,v 1.13 2008/04/07 15:00:56 kallie Exp $ **/ class TDBParams { private $owner = null; ///< Name of the object private $params = array(); ///< An array containing the params /*================================================================== SECTION: MAGIC methods ------------------------------------------------------------------*/ /** * TDBParams::__construct() * @brief The constructor setting up the TDBParams class object * * @param $owner **/ public function __construct(TDB $owner) { $this->owner = $owner; } //Create Parameter (Note: Param is NOT added to params array!.) public function NewParam($val, $name, $type = "auto") { $param = new TDBParam($this, $val, $name, $type); return $param; } /** * TDBParams::AddNamed() * @brief Add a parameter value with a name. * (Name can be empty) * * Add a parameter value with a name. (Name can be empty) * * @param $val The value of the parameter * @param $name The name of the parameter * @param $type The type of the parameter **/ public function AddNamed($val, $name, $type = "auto") { $param = $this->NewParam($val, $name, $type); $this->params[] = $param; } /** * TDBParams::Add() * @brief Add a parameter value (without a name) * * @param $val * @param $type * @return Null **/ public function Add($val, $type = "auto") { return $this->AddNamed($val, "", $type); } /** * TDBParams::AddList() * @brief Ads an array of values to the collection * * @param $values An array of parameter values * @param $type An array of parameter types **/ public function AddList($values, $type = "auto") { foreach($values as $key => $val) { //Array values should be added again if(is_array($val)) $this->AddList($val); //Numeric keys means the key is not a valid field name, so unset it if(is_numeric($key)) $key = ""; //Add parameter to list $this->AddNamed($val, $key, $type); } } /** * TDBParams::Set() * @brief It ads values passed as parameters * * $params->set('name',123,0.45); **/ public function Set() { $param_list = func_get_args(); $this->AddList($param_list); } /** * TDBParams::Clear() * @brief Clears collection of all values * **/ public function Clear() { $this->params = array(); } /** * TDBParams::Count() * @brief Returns number of values in collection * * @return Number of values **/ public function Count() { return count($this->params); } /** * TDBParams::ByIndex() * @brief Returns a TDBParam based on index position * * @param $index The index of the parameter value to return * @return a TDBParam object **/ public function ByIndex($index) { if($index<0) throw new Exception("TDBParams.ByIndex: Index out of range (Index=$index)."); if($index>=$this->count()) throw new Exception("TDBParams.ByIndex: Index out of range (Index=$index)."); return $this->params[$index]; } /** * TDBParams::ByName() * @brief Returns a TDBParam based on name * Returns FALSE if param not found * * @param $name Name of the TDBParam * @return The parameter of false if not found **/ public function ByName($name) { foreach($this->params as $param) if ($param->name==$name) return $param; return FALSE; } /** * TDBParams::escape_string() * @brief Generates a proper SQL string from value that is also SQL Injection safe * * @param $val The string so make SQL Injection safe. * @return SQL Injection safe string **/ public function escape_string($val) { return $this->owner->escape_string($val); } } //TDBParam class //############################################################################## /** * TSQLParser * * @author SpacialDev CC * @version $Id: class.db.php,v 1.13 2008/04/07 15:00:56 kallie Exp $ **/ class TSQLParser { public $param_count = 0; ///< A parameter counter /** * TSQLParser::ProcessParams() * @brief Parse SQL string to locate all parameters * * @param $sql Sql string to parse * @param TDBParams::$params Params class * @return Sql string with params inserted **/ public function ProcessParams($sql, TDBParams $params) { $escaped = false; ///< Is the character escaped? $escapechars = explode(",","\",',`"); ///< Escape characters $res = ""; ///< The result value $cnt = 0; ///< Internal counter $max = $params->Count(); ///< Maximum based on parameter count for($i=0;$i0) && (substr($sql,$i-1,1)=="\\"))) $escaped = !$escaped; if($char==":" && !$escaped) { //Check parameter count, then get current param if($cnt>$max) throw new Exception("TSQLParser.ProcessParams: Param count does not match."); $param = $params->ByIndex($cnt); $res .= $param->AsString(); $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; } $this->param_count = $cnt; return $res; } } //TSQLParser class //############################################################################## /** * @example class.db.example.php * @brief This is an example of how to use the database class */ /** * TDB * @brief Database abstraction layer for the MySQL database using the new mysqli API * * The top priority of this class is to provide a quick and easy programming layer * that hides most of the complexity of the mysqli interface without sacrificing * too much speed and flexibility. * * @author SpacialDev CC * @version $Id: class.db.php,v 1.13 2008/04/07 15:00:56 kallie Exp $ **/ class TDB { private $host = "localhost"; ///< The mysql database host private $username = "root"; ///< The mysql database username private $password = ""; ///< The mysql database password private $database = "mysql"; ///< The mysql database database private $error_email = "debug@spacialaudio.com"; ///< Email to send error reports to private $params = null; ///< SQL Parameters private $mysqli = null; ///< The mysqli object private $result = null; ///< The mysqli resultset private $stmt = null; ///< The sql statement private $mode = null; ///< The mysql mode: prepared, query, execsql private $err = null; ///< The last error if it should occur public $sqllog = array(); ///< Log of SQL statements public $logsql = false; ///< Must we log all SQL calls? public $shadowdb = false; ///< None of the queuries execute - the actual SQL are just logged! public $error_level = 6; ///< Error level (6=Hidden error, Exit) public $delayedconnect = true; ///< Wait until the first query before we connect? /*================================================================== SECTION: Magic methods ------------------------------------------------------------------*/ /** * TDB::__construct() * @brief The constructor setting up the TDB class * **/ public function __construct() { $this->params = new TDBParams($this); //If we are on a development server, set error level to 1 for easy debugging if (get_cfg_var( 'DEV-SERVER')) $this->error_level = 1; } /** * TDB::__clone() * Clones a TDB object * * @return New TDB object **/ public function __clone() { } /*================================================================== SECTION: Private methods ------------------------------------------------------------------*/ /** * TDB::CheckShadowDB() * @brief Check if we are in Shadow mode and abort if we are. * * @param $operation The operation we are trying to do **/ private function CheckShadowDB($operation = "") { if($this->shadowdb) { $err = "Operation not allowed in shadow mode."; if(!empty($operation)) $err .= " ($operation)"; $this->Abort($err); } } /** * TDB::LogSQL() * @brief Adds a SQL statement to SQL log we keep * * @param $sql SQL string **/ private function LogSQL($sql) { $this->sqllog[] = $sql; } /** * TDB::BuildErrorDisplay() * @brief Format error data for nice display in HTML webpage or Email * * @param $err Array containg the errors * @param $mime Mime type string * @return Body string of the error email to send **/ private function BuildErrorDisplay($err, $mime = "html") { $body = array(); $body[] = "date=".Date("Y-m-d H:i:s"); $body[] = "script=$err[script]"; $body[] = "agent=$err[agent]"; if(!empty($err["referer"])) $body[] = "referer=$err[referer]"; if(!empty($err["method"])) $body[] = "method=$err[method]"; if(!empty($err["query_str"])) $body[] = "query_str=$err[query_str]"; if(!empty($err["post"])) $body[] = "POST=$err[post]"; $body[] = "code=$err[code]"; $body[] = "msg=$err[msg]"; if($mime=='html') { $body[] = "
SQL Query
".htmlentities($err["sql"])."
"; $body = implode("
",$body); } else { $body[] = "sql=$err[sql]"; $body = implode("\n",$body); } return $body; } /** * TDB::HandleError() * @brief Build the error array and display/email/handle error * * @return False if we reach the end of the function without result **/ private function HandleError() { global $SCRIPT_FILENAME, $QUERY_STRING, $REQUEST_METHOD, $HTTP_USER_AGENT, $HTTP_REFERER; $err = array(); $err["sql"] = $this->sql; $err["script"] = $SCRIPT_FILENAME; $err["query_str"] = $QUERY_STRING; $err["method"] = $REQUEST_METHOD; $err["agent"] = $HTTP_USER_AGENT; $err["referer"] = $HTTP_REFERER; if($_POST) $err["post"] = serialize($_POST); //No valid connection - so lets check for connection error if(($this->mysqli == NULL) || ($this->mysqli == FALSE)) { $err["code"] = mysqli_connect_errno(); $err["msg"] = mysqli_connect_error(); } //Check for prepared query errors else if(($this->mode == "prepared") && ($this->stmt != NULL) && ($this->stmt != FALSE)) { $err["code"] = $this->stmt->errno; $err["msg"] = $this->stmt->error; } //Finally check directly for errors else { $err["code"] = $this->mysqli->errno; $err["msg"] = $this->mysqli->error; } $this->err = $err; $err_display = "Database error occurred. Please try again or contact support at http://spacialaudio.com/support/support.html"; switch($this->error_level) { case 0 : //Unit testing mode //Do nothing break; case 6 : //No-email "production mode" error level for clusters //Display hidden error message $hidden = $this->BuildErrorDisplay($err, "email"); echo $err_display; echo ""; Exit(); break; case 5 : //Email "production mode" error level for clusters //No error message, Email error, DONT EXIT $body = $this->BuildErrorDisplay($err, "email"); mail($this->error_email, "[SQL] Error $err[code]", $body); break; case 4 : //Normal "production mode" error level //Email error, EXIT $body = $this->BuildErrorDisplay($err, "email"); mail($this->error_email, "[SQL] Error $err[code]", $body); echo $err_display; Exit(); break; case 3 : //Store error, no exit break; case 2 : //Display error, no exit $body = $this->BuildErrorDisplay($err, "html"); echo $body; break; case 1 : //Normal "development mode" error level default : //Display error, EXIT $body = $this->BuildErrorDisplay($err, "html"); echo $body; exit(); break; } return FALSE; } /** * TDB::Abort() * @brief 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 * * @param $msg Message to display when throwing an exception **/ private function Abort($msg) { throw new Exception("TDB.Abort: ".$msg); } /** * TDB::escape_string() * @brief Generates a valid SQL string from value that is also SQL Injection safe. * * Uses the database connection to ensure the string is formatted according * to the current character set * * @param $val String to make SQL Injection safe. * @return SQL Injection safe string **/ public function escape_string($val) { $this->connect_force(); //Make sure we are connected $val = "'".$this->mysqli->real_escape_string($val)."'"; return $val; } /*================================================================== SECTION: Private Cluster helper functions ------------------------------------------------------------------*/ private function RandomNodeID(&$nodes, $remove_node = null) { if(!is_null($remove_node) && is_numeric($remove_node)) unset($nodes[$remove_node]); if(count($nodes) <= 0) return -1; $rand_key = array_rand($nodes, 1); return $rand_key; } private function GetCacheString(&$nodes, $database, $preferred_host) { if(empty($database)) $database = $nodes[$preferred_host]["database"]; $user = $nodes[$preferred_host]["username"]; $pass = $nodes[$preferred_host]["password"]; return "dbc_".md5($user."_".$pass."_".$database); } /*================================================================== SECTION: Core SQL connection methods ------------------------------------------------------------------*/ /** * TDB::connect() * @brief Initialize database connection settings * * Id delayedconnect is false, will also establish the actual database connection * * @param $host The mysql host * @param $username The mysql username * @param $password The mysql password * @param $database The mysql database **/ public function connect($host = "", $username = "", $password = "", $database = "") { if(!empty($host)) $this->host = $host; if(!empty($username)) $this->username = $username; if(!empty($password)) $this->password = $password; if(!empty($database)) $this->database = $database; if(($this->logsql) || ($this->shadowdb)) $this->LogSQL("USE ".$this->database); //Connect only if not ShadowDB, and not when delayed connects if(!$this->shadowdb && !$this->delayedconnect) $this->connect_force(); } /** * TDB::connectdb() * @brief Same as TDB::connect, except connection parameters is passed in an array * * The database name can either be inside the array, or be passsed as the * second parameter * * @param $dblogin Database login details in array format * @param $database Database to connect to * @see TDB::connect() * @see TDB::connectcluster() **/ public function connectdb($dblogin, $database = '') { if(empty($database)) $database = $dblogin["database"]; return $this->connect($dblogin["host"],$dblogin["username"],$dblogin["password"],$database); } /** * TDB::connectcl() * Private function that share common functionality in the * TDB::ConnectCluster() function * * @param mixed $node * @param mixed $database * @return * @see TDB::ConnectCluster() */ private function connectcl($node, $database) { $this->connectdb($node, $database); return $this->ValidLink(); } /** * TDB::ConnectCluster() * * @param mixed $nodes * @param integer $mainnodeID The preferred node. -1 means pick random node. * @param mixed $cache * @param string $database Database to connect to * @see TDB::connect() * @see TDB::connectdb() */ public function ConnectCluster($nodes, $mainnodeID = 0, Zend_Cache_Core $cache, $database = '') { //walk($nodes); //walk($mainnodeID); //var_dump($cache); //walk($database); { //Step 1: set environment varaibles $this->delayedconnect = false; //Make sure we instantly connect $this->error_level = 5; //Set the error level to cluster mode $connected = false; //Our default setting is false $nodeID = $mainnodeID; $this->selected_node = $nodeID; //For nodeID returning purposes } { //Step 2: Get the database details from cache and connect to that database $cache_string = $this->GetCacheString($nodes, $database, $nodeID); //Check if the cache contains the db details $cache_node = $cache->load($cache_string); if(!empty($cache_node)) { if(empty($database)) $database = $cache_node["database"]; $connected = $this->connectcl($cache_node, $database); } } { //Step 3: If not connected, try the preferred host if(!$connected && $nodeID >= 0) { if(!empty($cache_node["nodeID"])) unset($nodes[$cache_node["nodeID"]]); //unset it because it was in cache and failed if(!empty($cache_node["nodeID"]) && ($cache_node["nodeID"] == $nodeID)) $connected = false; else { $nodeID = $nodeID; if(empty($database)) $database = $nodes[$nodeID]["database"]; $connected = $this->connectcl($nodes[$nodeID], $database); } } //Set mainnode to -1 to try and connect to another random node if(!$connected) $nodeID = -1; } { //Step 4: As a last resort try to connect to a random node if(!$connected && $nodeID == -1) { //Get a random node $nodeID = $this->RandomNodeID($nodes); if(empty($database)) $database = $node["database"]; $connected = $this->connectcl($nodes[$nodeID], $database); while(!$connected) { $nodeID = $this->RandomNodeID($nodes, $nodeID); if($nodeID == -1) $this->Abort("Could not connect to any cluster database"); $connected = $this->connectcl($nodes[$nodeID], $database); } } } { //Step 5: Set the connected node to cache if nodeID > 0 AND the current cache is empty. //This allows us to let the cache expire so we can check if the preferred node is available. if($nodeID >= 0 && empty($cache_node)) { $nodes[$nodeID]["nodeID"] = $nodeID; $cache->save($nodes[$nodeID], "$cache_string"); } } //Step 6: If we are not connected, Abort with error message if(!$connected) { $this->error_level = 4; //Set the error level to production standard $this->HandleError(); //Abort with error message } else $this->selected_node = $nodeID; } public function GetClusterSelectedNode() { return $this->selected_node; } /** * TDB::connect_force() * @brief Make the actual connection to the database * * @return Boolean True if Connected else False **/ public function connect_force() { if(!$this->ValidLink()) @$this->mysqli = new mysqli($this->host, $this->username, $this->password, $this->database); if(mysqli_connect_errno()) { $this->mysqli = null; $this->HandleError(); return false; } else return true; } /** * TDB::selectdb() * @brief Change the current working database of the connection * * @param $database Name of the new database **/ public function selectdb($database) { if($this->database!=$database) { if(($this->logsql) || ($this->shadowdb)) $this->LogSQL("USE ".$this->database); $this->database = $database; if($this->ValidLink()) $this->mysqli->select_db($this->database); } } /** * TDB::close() * @brief Close down the database connection. * * This should be done as soon as no more queries need to be made in the script. * Keeping database connections open until the end of the script when the garbage collector disposes of them * results in wasted resources as the connection can not be re-used during that time. * * @return True or the result set **/ public function close() { //Get rid of any errors $this->err = null; //Dispose of any result sets $this->query_close(); //Clear params $this->params->clear(); if($this->mysqli || $this->ValidLink()) { $res = $this->mysqli->close(); $this->mysqli = null; return $res; } else return true; } /** * TDB::ValidLink() * @brief Tests if the database connection has been created * * Note: In delayedconnect mode you must first call $db->connect_force() * to create the connection or execute an SQL statement to connect to the * database * * @return True if Link is valid else False **/ public function ValidLink() { $this->CheckShadowDB("ValidLink"); return (($this->mysqli != FALSE) && ($this->mysqli != NULL)); } /** * TDB::HasError() * @brief Check if database errors has been found * * @return TRUE if any database errors have been detected **/ public function HasError() { return $this->err != null; } /*================================================================== SECTION: BASE SQL commands ------------------------------------------------------------------*/ /* $db->query("SELECT * FROM city"); $db->query("SELECT * FROM city",1); //Return only one row $db->query("SELECT * FROM city",1,10); //Return only one row, starting at position 10 $db->query("SELECT * FROM city WHERE ID = :ID",1,10,123); //Return only one row, starting at position 10 where ID = 123 $db->AddInt(123); $db->query("SELECT * FROM city WHERE ID = :ID"); //Return record with ID = 123 */ /** * TDB::query() * @brief Used to execute queries that returns a result set, i.e. SELECT queries * * @param $sql The sql query to execute * @param $limit Optional SQL LIMIT integer * @param $skip Optional SQL skip/START at posistion integer * @return TRUE on success, FALSE on failure (Or aborts according to error level) * * @see TDB::num_rows() * @see TDB::row() * @see TDB::query_close() * **/ public function query($sql, $limit = 0, $skip = 0) { //Dispose of any previous query results $this->query_close(); $this->mode = "query"; //If we have filled parameters, use them if($this->params->count()>0) { $parser = new TSQLParser(); $sql = $parser->ProcessParams($sql, $this->params); $this->params->Clear(); } //Connect if needed if(!$this->shadowdb && !$this->ValidLink()) $this->connect_force(); //Handle limit and start position of result set $skip = (int)$skip; $limit = (int)$limit; if($limit>0) { if($skip>0) $sql .= " LIMIT $skip, $limit"; else $sql .= " LIMIT $limit"; } //Store SQL statement - handy for debugging $this->sql = $sql; //Log SQL if needed if(($this->logsql) || ($this->shadowdb)) $this->LogSQL($this->sql); if(!$this->shadowdb) { $res = ($this->result = $this->mysqli->query($this->sql)); if(!$res) $this->HandleError(); return $res; } else return false; } /** * TDB::BatchExecute() * @brief Executes one or more SQL statements (Seperated via ;) * * Statements may include standard SQL and MySQL comments * * @param $sql The sql statements to execute * @return TRUE if ALL statements were successful, FALSE if any failed. (Or aborts according to error level) * * @warning While batch queries "may" contain SELECT statements, the DB * class does not allow you to process these results. It is assumed you * will only use it for ExecSQL style queries. **/ public function BatchExecute($sql) { //Dispose of any previous query results $this->query_close(); $this->mode = "query"; //Connect if needed if(!$this->shadowdb && !$this->ValidLink()) $this->connect_force(); //Store SQL statement - handy for debugging $this->sql = $sql; //Log SQL if needed if(($this->logsql) || ($this->shadowdb)) $this->LogSQL($this->sql); if(!$this->shadowdb) { $res = $this->mysqli->multi_query($sql); if($res) { //Run through each query to detect errors //Note: While we COULD have also read the results, we do not expect any results in batch queries do { /* store first result set - but immediately ignore it */ if ($result = $this->mysqli->store_result()) $result->close(); } while ($this->mysqli->next_result()); if($this->mysqli->errno) $this->HandleError(); } if(!$res) $this->HandleError(); return $res; } else return false; } /** * TDB::BatchExecuteFile() * @brief Works same as TDB::BatchExecute, except contents is loaded from file. * * @param $filename Filename to process * @return True if executed else False * * @see TDB::BatchExecute() **/ public function BatchExecuteFile($filename) { if(!file_exists($filename)) return false; $sql = file_get_contents($filename); if($sql) return $this->BatchExecute($sql); else return false; } /** * TDB::Open() * @brief Alias to TDB::query * * @see TDB::query() **/ public 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->params->AddList(array_slice($param_list,3)); } return $this->query($sql, $limit, $skip); } /** * TDB::OpenEx() * @brief Special alias to TDB::Query where the LIMIT and START values are removed * * Thus any parameters can be added in the argument list. * $db->OpenEx("SELECT * FROM city WHERE ID IN (:ID1,:ID2)",123,456); * * @param $sql SQL statement to execute **/ public function OpenEx($sql) { //Additional arguments passed are used as SQL Parameters if(func_num_args()>1) { $param_list = func_get_args(); $this->params->AddList(array_slice($param_list,1)); } $this->open($sql); } /* @example $db->execsql("DELETE FROM city"); $db->execsql("DELETE FROM city WHERE ID = :ID",123); $db->execsql("DELETE FROM city WHERE (ID > :ID) AND (cityname = :cityname)",123,'Lubbock'); $db->AddInt(123); $db->AddStr('Lubbock'); $db->execsql("DELETE FROM city WHERE (ID > :ID) AND (cityname = :cityname)"); */ /** * TDB::execsql() * @brief Executes an SQL query where no result set is expected, i.e. UPDATE, DELETE, INSERT, REPLACE, etc. * * @param $sql SQL statement to execute * @return TRUE on success, FALSE on failure (Or aborts according to error level) **/ public function execsql($sql) { //Dispose of any previous query results //$this->query_close(); $this->mode = "execsql"; //Additional arguments passed are used as SQL Parameters if(func_num_args()>1) { $param_list = func_get_args(); $this->params->AddList(array_slice($param_list,1)); } //If we have filled parameters, use them if($this->params->count()>0) { $parser = new TSQLParser(); $sql = $parser->ProcessParams($sql, $this->params); $this->params->Clear(); } //Connect if needed if(!$this->shadowdb && !$this->ValidLink()) $this->connect_force(); //Store SQL statement - handy for debugging $this->sql = $sql; //Log SQL if needed if(($this->logsql) || ($this->shadowdb)) $this->LogSQL($this->sql); if(!$this->shadowdb) { $res = ($this->result = $this->mysqli->query($this->sql)); if(!$res) $this->HandleError(); return $res; } else return false; } /** * TDB::insert_id() * @brief Returns the primary key of last inserted record * * This function workes for both prepared and normal queries * * @return The ID if the inserted row **/ public function insert_id() { $this->CheckShadowDB("insert_id"); if($this->mode == "prepared") return $this->stmt->insert_id; else return $this->mysqli->insert_id; } /** * TDB::num_rows() * @brief Gets the number of rows in the result set * * @return Ingeger number of rows * @warning Currently we call store result after queries, so we should always get an accurate count. * This function workes for both prepared and normal queries **/ public function num_rows() { $this->CheckShadowDB("num_rows"); if($this->mode == "prepared") return $this->stmt->num_rows; else { if($this->result) return $this->result->num_rows; else $this->Abort("num_rows: No valid result set."); } } /** * TDB::affected_rows() * @brief Returns the number of changed or deleted in the last SQL query * * This function workes for both prepared and normal queries * * @return String with the number of affected rows **/ public function affected_rows() { $this->CheckShadowDB("affected_rows"); if($this->mode == "prepared") return $this->stmt->affected_rows; else return $this->mysqli->affected_rows; } /** * TDB::row() * @brief Returns all the values in an associative array * * If fieldname is specified, only returns the fieldname * This function workes for both prepared and normal queries * * @param $fieldname Name of the field who's value we want to retrieve * @return Mixed value of the field specified **/ public function row($fieldname = "") { if($this->mode=="prepared") $res = ($row = $this->query_row()); elseif(is_object($this->result)) $res = ($row = $this->result->fetch_assoc()); else $res = FALSE; if($res && $row && is_array($row)) { if(empty($fieldname)) $res = $row; else $res = $row[$fieldname]; } else $res = FALSE; return $res; } /** * TDB::rows() * @brief Returns all the rows in the result set * * If the fieldname is specified, returns all the values of the fieldname as array * * @param $fieldname If specified, return only array of this field * @return Array with record data **/ public function rows($fieldname = "") { $rows = array(); while($val = $this->row()) $rows[] = $val; return $rows; } /*================================================================== SECTION: Prepared queries ------------------------------------------------------------------*/ /** * TDB::query_prepare() * @brief Executes a query from a prepared statement * * @param $sql Prepared statement sql * @return The result object **/ public function query_prepare($sql) { //Dispose of any previous query results $this->query_close(); $this->mode = "prepared"; $this->stmt = $this->mysqli->stmt_init(); $res = $this->stmt->prepare($sql); if(!$res) $this->HandleError(); return $res; } /** * TDB::query_execute() * @brief Execute a prepared query * **/ public function query_execute() { /* bind parameters for markers */ $cnt = $this->params->count(); if($cnt>0) { $bindParams = array(); $bindtypes = ""; $bindParams[0] = "Place holder!"; for($i=0;$i<$cnt;$i++) { $param = $this->params->ByIndex($i); $bindtypes .= $param->bindtype(); $bindParams[] = $param->value; } $this->params->clear(); //Clear out parameters $bindParams[0] = $bindtypes; $res = @call_user_func_array(array($this->stmt, 'bind_param'), $bindParams); if(!$res) $this->Abort("Error during parameter bind. Most likely incorrect param count."); } /* execute query */ $res = $this->stmt->execute(); if($res) { $meta = $this->stmt->result_metadata(); if($meta != null) { while ($column = $meta->fetch_field()) { $columnName = str_replace(' ', '_', $column->name); $bindVarArray[] = &$this->stmt->results[$columnName]; } call_user_func_array(array($this->stmt, 'bind_result'), $bindVarArray); $this->varsBound = true; $this->stmt->store_result(); } } else $this->HandleError(); } /** * TDB::query_row() * @brief Fetch values into bound variables * * @return Resultset or False if none **/ public function query_row() { if ($this->stmt->fetch() != null) { foreach ($this->stmt->results as $k => $v) $results[$k] = $v; return $results; } else return false; } /** * TDB::query_close() * @brief Close query and dispose of the resultset etc. * * @return Result object **/ public function query_close() { $this->mode = null; if(!is_null($this->stmt)) { $this->stmt->free_result(); $res = $this->stmt->close(); } $this->stmt = null; if(is_object($this->result)) $res = $this->result->close(); $this->result = null; return $res; } /*================================================================== SECTION: Array/Object based quick operations ------------------------------------------------------------------*/ /** * TDB::BuildQuery() * @brief Handels the construction of a query based on the params received * * @param $data Data to be translated into Params * @param $type The type of query: insert or update * @param $fields Reference to the fields to add * @param $values Reference to the values to add * @return True if successfull **/ private function BuildQuery($data, $type, &$fields, &$values) { $myparams = $this->params; $fields = array(); $values = array(); //Translate data into params: Data can be Null, Array or TDBParams if(is_array($data)) { foreach($data as $field => $value) $this->params->AddNamed($value,$field); } else if(is_object($data) && is_a($data->class_name,"TDBParams)")) { if($this->params->count()<=0) $this->Abort("TDB.BuildQuery: Params passed as data value, but dataset already contains params."); $myparams = $data; } else if($data==null) { if($this->params->count()<=0) $this->Abort("TDB.BuildQuery: Null data value passed and TDB->params is empty."); } else $this->Abort("TDB.BuildQuery: Data passed is not valid. Must be Null, Array or TDBParams."); $max = $myparams->count(); for($i=0;$i<$max;$i++) { $param = $myparams->ByIndex($i); if(empty($param->name)) $this->Abort("TDB.BuildQuery: One or more paramters does not have any names."); switch($type) { case "insert" : $values[] = $param->AsString(); $fields[] = $param->name; break; case "update" : $values[] = $param->name . " = " . $param->AsString(); break; default : $this->Abort("TDB.BuildQuery: Invalid query build type ($type)."); break; } } $values = implode(",",$values); $fields = implode(",",$fields); //Clear processed params $this->params->clear(); return true; } /** * TDB::insert() * @brief Public interface to insert the data passed into the database * * @param $table The table to insert data into * @param $data The data to insert into the table * * @return True when completed **/ public function insert($table, $data = null) { $this->BuildQuery($data, "insert", $fields, $values); return $this->execsql("INSERT INTO $table ($fields) VALUES ($values)"); } /** * TDB::insertdelayed() * @brief Same as TDB::insert but inserted with a delay * * @param $table The table to insert data into * @param $data The data to insert into the table * * @return True when completed * @see TDB::insert() **/ public function insertdelayed($table, $data = null) { $this->BuildQuery($data, "insert", $fields, $values); return $this->execsql("INSERT DELAYED INTO $table ($fields) VALUES ($values)"); } /** * TDB::replace() * @brief Public interface to replace existing data with the data passed * * @param $table The table to insert data into * @param $data The data to replace * * @return True when completed **/ public function replace($table,$data = null) { $this->BuildQuery($data, "insert", $fields, $values); return $this->execsql("REPLACE INTO $table ($fields) VALUES ($values)"); } /** * TDB::replacedelayed() * @brief Same as TDB::replace but replaced with a delay * * @param $table The table to replace data into * @param $data The data to replace * * @return True when completed **/ public function replacedelayed($table, $data = null) { $this->BuildQuery($data, "insert", $fields, $values); return $this->execsql("REPLACE DELAYED INTO $table ($fields) VALUES ($values)"); } /** * TDB::update() * @brief Used to update a table on some conditions * * $table = Name of table where to update data * $data = Can be a TDBParams object, Associative Array or NULL * $where = WHERE clause * * a) Assume primary key is called "ID" * $db->update("mytable",$data,1); * b) Specifically specify where clause * $db->update("mytable",$data,"ID = 1"); * c) Alternative parameter usage * $db->update("mytable",$data,"ID = :ID",1); * d) NOTE: This does NOT work! * $db->AddInt(1); * $db->update("mytable",$data,"ID = :ID"); * * @param $table The table to be updated * @param $data The data to update * @param $where Condition for updating table * @return True * * @warning For safety reasons we do not allow an update without a where clause If you really need to update all records, either build the query yourself or alternatively use a where clause that is aleays true, i.e. $db->update("mytable",$data,"1=1"); **/ public function update($table, $data, $where) { if(is_numeric($where)) $where = "ID = $where"; $this->BuildQuery($data, "update", $dummy, $updates); //Additional arguments passed are used as SQL Parameters //NOTE: These are processed AFTER the UPDATE part of the query has been built if(func_num_args()>3) { $param_list = func_get_args(); $this->params->AddList(array_slice($param_list,3)); } return $this->execsql("UPDATE $table SET $updates WHERE $where"); } /* Usage: a) Assume primary key is called "ID" $db->delete("mytable",1); b) Specifically specify where clause $db->delete("mytable","ID = 1"); c) Use parameters in where clause - more SQL Injection safe $db->AddInt(1); $db->delete("mytable","ID = :ID"); d) Alternative parameter usage $db->delete("mytable","ID = :ID",1); Note: For safety reasons we do not allow a delete without a where clause To totally clear a table, use $db->Truncate("mytable"); */ /** * TDB::delete() * @brief Used to delete records in a table * * Assume primary key is called "ID" * $db->delete("mytable",1); * b) Specifically specify where clause * $db->delete("mytable","ID = 1"); * c) Use parameters in where clause - more SQL Injection safe * $db->AddInt(1); * $db->delete("mytable","ID = :ID"); * d) Alternative parameter usage * $db->delete("mytable","ID = :ID",1); * * @param $table The table name to delete from * @param $where The condition for the delete operation to work * @return True **/ public function delete($table, $where) { //Additional arguments passed are used as SQL Parameters if(func_num_args()>2) { $param_list = func_get_args(); $this->params->AddList(array_slice($param_list,2)); } if(is_numeric($where)) $where = "ID = $where"; return $this->execsql("DELETE FROM $table WHERE $where "); } /** * TDB::insertupdate() * @brief Used to insert a new record but if it exists update the existing record * * @param $table The table to do the operations on * @param $insertdata Array with data to insert * @param $updatedata Array with data to update * @return True **/ public function insertupdate($table, $insertdata, $updatedata) { $this->BuildQuery($insertdata, "insert", $fields, $values); $this->BuildQuery($updatedata, "update", $dummy, $updates); return $this->execsql("INSERT INTO $table ($fields) VALUES ($values) ON DUPLICATE KEY UPDATE $updates"); } /** * TDB::Truncate() * @brief Truncates a table specified * * @param $table Table name to truncate * @return True **/ public function Truncate($table) { return $this->execsql("TRUNCATE TABLE $table"); } /*================================================================== SECTION: Transaction operations ------------------------------------------------------------------*/ /** * TDB::transaction_new() * @brief Starts a new transaction * * @return True **/ public function transaction_new() { return $this->execsql("START TRANSACTION"); } /** * TDB::transaction_commit() * @brief Commits a current tansaction * * @return True **/ public function transaction_commit() { return $this->execsql("COMMIT"); } /** * TDB::transaction_rollback() * @brief Do a rollback of the current transaction * * @return **/ public function transaction_rollback() { $this->CheckShadowDB("transaction_rollback"); //Make no sense in shadowdb to rollback a transaction return $this->execsql("ROLLBACK"); } /*================================================================== SECTION: General Helper methods ------------------------------------------------------------------*/ /** * TDB::HashTableName() * @brief Returns a HastableName adding the hashID to the table name provided * * @param $table The table name * @param $hashID A hashID to add to the table name * @param $max The maximum integer size * @return Hashed table name **/ public function HashTableName($table, $hashID, $max = 32) { $c = ($hashID % $max); $table = sprintf("%s%02d", $table, $c); return $table; } /** * TDB::DatabaseExists() * @brief Checks to see if a certain database exists * * @param $DatabaseName The name of the database to check * @return True if found else False **/ public function DatabaseExists($DatabaseName) { $this->CheckShadowDB("DatabaseExists"); $this->AddStr($DatabaseName); $this->query("SHOW DATABASES LIKE :dbname"); if($this->num_rows()>0) { $temp = each($this->row()); $row = $temp["value"]; if ($row == $DatabaseName) return true; } return false; } /** * TDB::TableExists() * @brief Checks to see if a certain table exists * * @param $TableName The name of the table to check * @return True if found else False **/ public function TableExists($TableName) { $this->CheckShadowDB("TableExists"); $this->AddStr($TableName); $this->query("SHOW TABLES LIKE :table"); if($this->num_rows()>0) { $temp = each($this->row()); $row = $temp["value"]; if ($row == $TableName) return true; } return false; } /** * TDB::FieldNames() * @brief Gets the fieldnames from a table specified * * @param $table The table to retrieve fieldnames from * @return Array with the fieldnames retrieved from the table **/ public function FieldNames($table) { $this->CheckShadowDB("FieldNames"); $fields = array(); $this->AddStatement($table); $this->query("SHOW COLUMNS FROM :table"); while($row = $this->row()) { $row = each($row); $fields[] = $row["value"]; } return $fields; } /** * TDB::FieldEnumValues() * @brief Retrieves the Enumeration or Set values from a certain field in a table * * @param $table The table to check * @param $field The field to retrieve Enum or Set name from * @return Array with names or empty array if none **/ public function FieldEnumValues($table, $field) { $this->CheckShadowDB("FieldEnumValues"); // Query Database for field structure $this->AddStatement($table); $this->AddStr($field); $this->query("SHOW COLUMNS FROM :table LIKE :field"); // Get the data $data = $this->row(); if ((substr_count($data["Type"], "enum") > 0) or (substr_count($data["Type"], "set") > 0)) { // format Enum vars into an array return explode("','",preg_replace("/(enum|set)\('(.+?)'\)/","\\2",$data["Type"])); } else return array(); } public function CloneSettings() { $dblogin = array(); $dblogin['host'] = $this->host; $dblogin['username'] = $this->username; $dblogin['password'] = $this->password; $dblogin['database'] = $this->database; return $dblogin; } /*================================================================== SECTION: Aliases for methods A lot of names were added for backwards compatibility ------------------------------------------------------------------*/ /* function next() function getrow() function getrows() function recordcount() function NewTransaction() function commit() function rollback() function BatchExecute($sql) function GetFieldNames($table) FUNCTION GetEnumValues( $table, $field ) function forceconnect() */ /*================================================================== SECTION: Parameter handling ------------------------------------------------------------------*/ /** * TDB::AddStr() * @brief Adds a String parameter to the object * * Alias to TDB::AddString * * @param $val The value of the parameter * @param $name The name of the parameter * @see TDB::AddString() **/ public function AddStr($val, $name = "") { $this->params->AddNamed($val,$name,"string"); } /** * TDB::AddString() * @brief Adds a String parameter to the object * * Alias to TDB::AddStr * * @param $val The value of the parameter * @param $name The name of the parameter * @see TDB::AddStr() **/ public function AddString($val, $name = "") { $this->params->AddNamed($val,$name,"string"); } /** * TDB::AddInt() * @brief Adds a Integer parameter to the object * * Alias to TDB::AddInteger * * @param $val The value of the parameter * @param $name The name of the parameter * @see TDB::AddInteger() **/ public function AddInt($val, $name = "") { $this->params->AddNamed($val,$name,"integer"); } /** * TDB::AddInteger() * @brief Adds a Integer parameter to the object * * Alias to TDB::AddInt * * @param $val The value of the parameter * @param $name The name of the parameter * @see TDB::AddInt() **/ public function AddInteger($val, $name = "") { $this->params->AddNamed($val,$name,"integer"); } /** * TDB::AddFloat() * @brief Adds a Float parameter to the object * * @param $val The value of the parameter * @param $name The name of the parameter **/ public function AddFloat($val, $name = "") { $this->params->AddNamed($val,$name,"double"); } /** * TDB::AddDouble() * @brief Adds a Double parameter to the object * * @param $val The value of the parameter * @param $name The name of the parameter **/ public function AddDouble($val, $name = "") { $this->params->AddNamed($val,$name,"double"); } /** * TDB::AddDate() * @brief Adds a Date parameter to the object * * @param $val The value of the parameter * @param $name The name of the parameter **/ public function AddDate($val, $name = "") { $this->params->AddNamed($val,$name,"date"); } /** * TDB::AddTime() * @brief Adds a Time parameter to the object * * @param $val The value of the parameter * @param $name The name of the parameter **/ public function AddTime($val, $name = "") { $this->params->AddNamed($val,$name,"time"); } /** * TDB::AddDateTime() * @brief Adds a DateTime parameter to the object * * @param $val The value of the parameter * @param $name The name of the parameter **/ public function AddDateTime($val, $name = "") { $this->params->AddNamed($val,$name,"datetime"); } /** * TDB::AddTimeStamp() * @brief Adds a TimeStamp parameter to the object * * @param $val The value of the parameter * @param $name The name of the parameter **/ public function AddTimeStamp($val, $name = "") { $this->params->AddNamed($val,$name,"datetime"); } /** * TDB::AddBool() * @brief Adds a Boolean parameter to the object * * @param $val The value of the parameter * @param $name The name of the parameter **/ public function AddBool($val, $name = "") { $this->params->AddNamed($val,$name,"boolean"); } /** * TDB::AddStatement() * @brief Adds a statement parameter to the object * * @param $val The value of the parameter * @param $name The name of the parameter **/ public function AddStatement($val, $name = "") { $this->params->AddNamed($val,$name,"statement"); } /** * TDB::AddNull() * @brief Adds a Null parameter to the object * * @param $name The name of the parameter **/ public function AddNull($name = "") { $this->params->AddNamed(NULL,$name,"null"); } //Special parameter that allows you to use functions safely public function AddFunc($func_name, $val, $name = "", $type = "auto") { $tmp = array(); $tmp["param"] = $this->params->NewParam($val, $name, $type); $tmp["function"] = $func_name; $this->params->AddNamed($tmp, $name, "function"); } }//TDB class /* $db = new TDB(); $db->delayedconnect = false; $db->connect("localhost","root","","bid4spots"); $sql = "SELECT 1; SELECT 2 FROM g"; $db->BatchExecute($sql); /* $data = array(); $data["age_start"] = 150; $data["age_end"] = 250; $db->insert("ages",$data); */ /* $db->query_prepare("SELECT * FROM ages WHERE age_start > 0"); $db->query_execute(); while($row = $db->query_row()) { var_dump($row); } $db->AddInt(1); $db->AddInt(2); $db->query_execute(); while($row = $db->row()) { var_dump($row); } /* */ /* $db->AddStatement('ages'); $db->AddInt(1); if($db->query("SELECT * FROM :table WHERE (ID = :ID)")) echo "Query good
"; else echo "Query failed!
"; $rows = $db->rows(); var_dump($rows); while($row = $db->row()) { var_dump($row); echo "
"; } $db->close(); /* */ ?>