Created
June 7, 2011 10:34
-
-
Save behringer24/1012015 to your computer and use it in GitHub Desktop.
Easy method to build SQL queries and escape parameters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Replacement callback function | |
* | |
* @param array $match | |
* @return string | |
*/ | |
private function queryReplacementCallback($match) { | |
if (!isset($this->queryReplacementData[$match[2]]) || $this->queryReplacementData[$match[2]] === null) { | |
$replace = 'null'; | |
} else { | |
switch ($match[1]) { | |
case 'd': $replace = (int) $this->queryReplacementData[$match[2]]; | |
break; | |
case 'f': $replace = (float) $this->queryReplacementData[$match[2]]; | |
break; | |
case 'S': $replace = $this->queryReplacementData[$match[2]]; | |
break; | |
default: $this->log("Unknown data type ".$match[1]." for ".$match[2]." in query", 'error'); | |
case 's': $replace = "'".$this->esc($this->queryReplacementData[$match[2]])."'"; | |
break; | |
} | |
} | |
return $replace; | |
} | |
/** | |
* Query database and escape parameters | |
* | |
* @param string $query SQL query | |
* @param array $data Dynamic data from data objects like e.g. acRow | |
* @param array $static_data Optional array with further static data like table or database names | |
*/ | |
public function query($query, $data = array(), $static_data = array()) { | |
$this->queryReplacementData = is_array($static_data) ? array_merge($data, $static_data) : $data; | |
$final_query = preg_replace_callback("/\{(s|S|d|f):([a-z0-9_]+)\}/i", array(&$this, 'queryReplacementCallback'), $query, -1, $count); | |
$this->log("Replaced ".$count." parameters in query ".$query, 'system'); | |
return $this->rawQuery($final_query); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Nw version done with preg_replace_callback()