0

In Drupal v7.22 I'm trying to order the query below for a custom module but I cannot seem to find documentation that fits this query.

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

I've found details on 'orderBy' but only with examples as below which are not in the same format as my query. Any help would be appreciated.

$query->groupBy("thread.sid");
$query->having("MAX(comment.created)");
$query->orderBy("comment.created", "DESC");
$result = $query->execute();
1
  • With db_query you need to write query on your own, like you would directly in sql client. That's all. No examples as they are on MySQL / Postgresql sites.
    – Mołot
    Commented Jun 22, 2013 at 8:40

1 Answer 1

3

Something like:

$query = db_select('tablename');
$query->fields('tablename', array('field1', 'field2'));
$query->condition('field3', $var1);
$query->condition('field4', $var2);
$query->orderBy('field1', 'DESC');

$result = $query->execute();

foreach($result as $row){
  // Debug
  drupal_set_message('<pre>'.print_r($row,1).'</pre>');
}

More info:

2
  • Thanks. Btw this line caused an error for me $query->fields('tablename', array('field1, field2')); and only worked once I changed it to $query->fields('tablename', array('field1', 'field2'));
    – RebDev
    Commented Jun 22, 2013 at 8:54
  • Thanks glad to hear it. Twas untested, but snippet tweaked to add those missing quotes. Commented Jun 22, 2013 at 8:59

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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