views:

98

answers:

3

Is this all to stop SQL injection in Drupal?

db_query('INSERT INTO {tablename} (field1, field2) VALUES ("%s", "%s")', $field1, $field2);
+4  A: 

You can use parameters, as described in the documentation.

However, you should call the drupal_write_record function instead.

SLaks
+3  A: 

Is your question "Is this all I need to do to stop SQL injection in Drupal?"

The answer is "Almost, but not quite."

db_query("INSERT INTO {tablename} (field1, field2) VALUES ('%s', '%s')", 
         $field1, $field2);

Single quotes are more standard for quoting values in SQL.

Alternately, if you've defined tablename table via hook_schema, you can use drupal_write_record instead, as the other answer states. The advantage of drupal_write_record is that you don't have to deal with any sql, you just do this:

$tablename = array('field1' => $field1, 'field2' => $field2);
drupal_write_record('tablename', $tablename);
John Fiala
Thanks for your suggestion. You mean `$field1 $field2` can be raw $POST data not sanitized at all by me? Is it fine? Drupal will just take care of it all?
jblue
They can be raw $_POST data, yes. I would suggest using the form api, which would then allow you to get the data out of $form_state['values'] instead, but drupal's code will handle any sort of raw data. If the values are fixed-length char/varchar fields, I'd recommend checking the string length before doing the insert anyway, because it's a good practice.
John Fiala
A: 

I strongly recommend using drupal_write_record() function instead of SQL instructions, as SLaks pointed before.

carles

related questions