Hi all,
I hope this is the wrong place where to post. I'm developing my very first Drupal Module and I was reading the code of some other modules to get an idea. I saw how they use the db_query() function, but I'm not 100% sure the approach is safe.
Let's take, for example, the following command:
db_query("select * from {my_table} where some_field = '%s'", $some_param);
As far as I understood, db_query simply uses sprintf() to replace the parameters, therefore it doesn't perform any "sanity check", nor it "fixes" them if they contain special characters. This means that, if I assign $some_param a typical SQL Injection value such as "' or 1=1;--", the resulting query would be the following:
select * from {my_table} where some_field = '' or 1=1;--'
I admit I didn't experiment thoroughly as the doubt came to my mind right now and I don't have a Drupal system available, but I hope I can still get the some experts' opinion.
At the moment, since I first started the module in Drupal 7, but I had to move back to Drupal 6 for compatibility reasons, I'm using a slightly more complicated approach and I fill the query parameters using the t() function, effectively passing a complete SQL Statement to db_query(). It brings some overhead, but it also allows me to see the full SQL (with values) before I pass it to the function; perhaps it's overkill, but, as a Drupal novice, I find it very useful. :)
Thanks in advance for all the replies.
Comments
The API is your friend
Might I suggest that you read through the API. The part on db_query should prove most useful. It's found here: db_query. Take a good read through the code of that function and (if you understand PHP code) you should be satisfied that queries passed through it are safe.
Not to put too fine a point on it, but do you actually think that in the 10 years that drupal has been around and the significant number of high profile sites running it, NOBODY bothered to check to see if the database abstraction layer was actually secure? One of the beautiful things about drupal, however, is the ability to do things your own way if reinventing the wheel is your cup of tea.
In database.inc line in
In database.inc line in function _db_query_callback you will find
code: return db_escape_string(array_shift($args));
Maybe help?
I fill the query parameters
/me checks date
Ehm? What!?
Please use the database API properly, with placeholders.
Will do. Pity that, in Drupal
Will do. Pity that, in Drupal 6, they are positional, I find them more difficult to manage.