1

I'm using the method below to query the database within a custom module but it doesn't seem to be the 'Drupal' way of doing things. Is there a better way?

$sql = "SELECT field1, field2 FROM {tablename} WHERE field3 = $var1 AND field4 = $var2";
$result = db_query($sql);
$num = $result->rowCount();
if ($num != null) {
  foreach($result as $line) {
    // Do something
  }
}
6

welcome.

The only tweak needed I see is:

$sql = "SELECT field1, field2 FROM {tablename} WHERE field3 = :var1 AND field4 = :var2";
$result = db_query($sql, array(':var1' => $var1, ':var2' => $var2));

The method you've written your query allows for SQL-Injection -- using placeholders in the SQL helps to defend against this.

I invite you to read up on the Database API documentation, specifically queries:

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.