If you take a look at the one significant line of code in db_query
:
return Database::getConnection($options['target'])->query($query, $args, $options);
you can see it just proxies the arguments straight through to the connection's query
method; if db_query
is safe, the connection's query
method is guaranteed to be safe too, because db_query($sql, $args);
and $connection->query($sql, $args);
are identical operations.
So all you need to do is maintain a combination of safe query string and parameters, and just pass them to the connection's query
method instead. Your queries will be safe.
As an aside, db_query()
only helps to prevent SQL injection if it's used properly. You can't save people from themselves. Case in point, these are perfectly valid:
db_query("SELECT * FROM foo WHERE var = '$_GET[baz]'");
Database::getConnection($options['target'])->query("SELECT * FROM foo WHERE var = '$_GET[baz]'");
but potentially deadly. Little Bobby will be on his way in no time.
Same goes for any other method. If you use parameters, and don't do crazy things like string interpolation/substitution to put user-supplied input into your SQL string, you're as safe as you can be.