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); | |
} |
Could be done with preg_replace_callback(). Would result in a much nicer code
Nw version done with preg_replace_callback()
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Example:
$sql = query(SELECT * FROM tablename WHERE username={s:name} AND email={s:email}, array('name' => 'My name', 'email' => '[email protected]'));
Possible improvement could be to pass tablenames etc without having to merge arrays of data params with database information params.
Do we need a data type for date, time and datetime?
Is a special flag for database fields that are set to 'not null' usefull (auto conversion to 0 or empty string)?