Skip to content

Instantly share code, notes, and snippets.

@behringer24
Created June 7, 2011 10:34
Show Gist options
  • Save behringer24/1012015 to your computer and use it in GitHub Desktop.
Save behringer24/1012015 to your computer and use it in GitHub Desktop.
Easy method to build SQL queries and escape parameters
/**
* 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);
}
@behringer24
Copy link
Author

If we make the type prefix optional the default case could be used very simple

@behringer24
Copy link
Author

Example:
$sql = query(SELECT * FROM tablename WHERE username={s:name} AND email={s:email}, array('name' => 'My name', 'email' => 'example@test.com'));

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)?

@behringer24
Copy link
Author

Could be done with preg_replace_callback(). Would result in a much nicer code

@behringer24
Copy link
Author

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