The 'Drupal' way to query the database 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-&gt;rowCount();
if ($num != null) {
  foreach($result as $line) {
    // Do something
  }
}
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' =&gt; $var1, ':var2' =&gt; $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:


Result Sets
Dynamic Queries
Static Queries