A kick-ass PHP mysql escaping function
Posted by Kelvin on 31 Jul 2010 at 12:33 pm | Tagged as: PHP, programming
Hate calling mysql_real_escape_string repeatedly in your code? Use these functions cobbled together from http://www.php.net/manual/en/function.mysql-real-escape-string.php
/** * USAGE: mysql_safe( string $query [, array $params ] ) * $query - SQL query WITHOUT any user-entered parameters. Replace parameters with "?" * e.g. $query = "SELECT date from history WHERE login = ?" * $params - array of parameters * * Example: * mysql_safe( "SELECT secret FROM db WHERE login = ?", array($login) ); # one parameter * mysql_safe( "SELECT secret FROM db WHERE login = ? AND password = ?", array($login, $password) ); # multiple parameters * That will result safe query to MySQL with escaped $login and $password. **/ function mysql_safe($query,$params=false) { if ($params) { foreach ($params as &$v) { $v = db_escape($v); } # Escaping parameters # str_replace - replacing ? -> %s. %s is ugly in raw sql query # vsprintf - replacing all %s to parameters $sql_query = vsprintf( str_replace("?","%s",$query), $params ); $sql_query = mysql_query($sql_query); # Perfoming escaped query } else { $sql_query = mysql_query($query); # If no params... } return ($sql_query); } /** * Automatically adds quotes (unless $quotes is false), but only for strings. Null values are converted to mysql keyword "null", booleans are converted to 1 or 0, and numbers are left alone. * Also can escape a single variable or recursively escape an array of unlimited depth. */ function db_escape($values, $quotes = true) { if (is_array($values)) { foreach ($values as $key => $value) { $values[$key] = db_escape($value, $quotes); } } else if ($values === null) { $values = 'NULL'; } else if (is_bool($values)) { $values = $values ? 1 : 0; } else if (!is_numeric($values)) { $values = mysql_real_escape_string($values); if ($quotes) { $values = '"' . $values . '"'; } } return $values; }
Usage
As a drop-in replacement for mysql_query when no placeholders (?) are used.
$result = mysql_safe("select 1 from table");
Use placeholders like so.
$result = mysql_safe("select ? from table where foo=?", array(1, "bar"));
The original mysql_safe function didn't escape numerics properly. The db_escape function does that nicely.