I got sick of writing queries in my PHP as:
"WHERE '" . Database::escape($var) . "'";
The escape() function just calls mysql_real_escape_string() - but it's there so I can extend support to other databases later.
Having to single quote strings in the query was making my code more cluttered. So my idea was to create an other function in my database class to 'prepare' a variable for a query:
static public function prepare($var)
{
if (is_object($var) || is_array($var) ) {
return " '" . Database::escape(serialize($var)) . "' ";
} else if (is_bool($var)) {
return ' ' . (int)$var . ' ';
} else if (is_int($var)) {
return ' ' . $var . ' ';
} else if (is_string($var) || is_float($var)) {
return " '" . Database::escape($var) . "' ";
} else {
throw new Exception('Unsupported variable type [' . gettype($var) . ']');
}
}
Now the benefit here is that, I don't need to worry about which variables I pass to a query. However it raises two questions:
- Am I handling each variable type properly?
- For what reason (if any) should I not do this?