1

I have the following query:

$query = "SELECT *
      FROM mytable
      {$typeClause}
      HAVING distance <= {$radius}
      ORDER BY distance ASC"
      GROUP BY type;

    $result = db_query($query);
    $points = array();

    while(($point = $result->fetchAssoc()) != null){
    }

In my db there is field 'type' which is a number
How can I get all records as an array without using the while statement above (something like fetchByGroup):

array(
        '1' => array( [all records of type=1] ),
        '2' => array( [all records of type=2] ),
        ......................................
    );
1
  • 1
    Drupal (and PDO) don't have any such helper method as far as I know
    – Clive
    Feb 19, 2014 at 18:59

2 Answers 2

2

You cannot do this using native Drupal 7 functionality. You need to do that grouping in PHP. You should be using a foreach, not a while loop :)

The most common case is to iterate over the result set with a foreach() loop.

Source: https://drupal.org/node/1251174

0

fetchAllAssoc($field) will do the magic for you.

$query = "SELECT *
      FROM mytable
      {$typeClause}
      HAVING distance <= {$radius}
      ORDER BY distance ASC"
      GROUP BY type;

    $result = db_query($query)->fetchAllAssoc('fieldname');

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.