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->orderBy("comment.created", "DESC");
$result = $query->execute();
  • 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 Jun 22 '13 at 8:40

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

More info:

  • 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 Jun 22 '13 at 8:54
  • Thanks glad to hear it. Twas untested, but snippet tweaked to add those missing quotes. – David Thomas Jun 22 '13 at 8:59

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.