PHP sqlwrap for psuedo-bound parameters 20 Feb, 2006
If only PHP had iterators, and exceptions backported to php4, the world would be a better place. At least that’s what I tell myself. I use a couple of wrappers to make things more palatable, although they’re, in a sense, leaky abstractions.
function sqlwrap() { $params = func_get_args(); $q = array_shift($params); array_walk($params, 'esc'); $query = vsprintf($q, $params); return $query; } function esc(&$s) { if(!is_numeric($s)) $s = "'".addslashes($s)."'"; }
This allows you to pretend you’re binding parameters, ala:
$qh = mysql_query(sqlwrap( "SELECT * FROM somedb WHERE username=%s or userage>%d", "bob", 23)) or die("Query Error");
While this does not seem immediately productive to some, imagine that magic_quotes_gpc
are disabled (as they ought to be!), this pushes the escaping function over to the database layer by saying “this is a string, deal with it.” One peeve I have about PHP (which I promptly fix via php.ini
) is that magic_quotes_gpc
affects all data, assuming that they go straight to the database and not to the screen, like, ever. You can safely pass things straight from $_REQUEST
into the second parameter and beyond of sqlwrap
, it handles escaping for you.
If you need to put literal in there that shouldn’t be escaped, then put them directly into the query string before passing it to sqlwrap
. In this way, the abstraction is not terribly leaky, and you retain control over things when you need it. I haven’t included support for LIKE
queries’ escaping, that’s something that really ought to have a human touch to deal with correctly. (Strip ‘%’ and ‘?’ from params, then use sqlwrap
on the resulting sanitized string.) In this way, you get all the benefits of bound parameters, except speed.