What I'm sure is a straightforward question to answer, only made difficult by my lack of understanding...

I have retrieved a number of rows from the database using db_query, returning the data as an object using db_fetch_object**

I would like to display data from each of these rows.

**My obvious error. db_fetch_object works only for single rows.

What I need to to is to return an array of objects corresponding to the individual rows.

How do I achieve this?

Thanks

Comments

Nooby-1’s picture

It is possible to use db_num_rows to find the number of rows returned by a query.

Then use this result to iterate through individual rows, returning single objects in series.

The result that is returned is fine as I need to retrieve every row of a particular table.

Would it be possible to retrieve all the data in one query and then split the data into individual objects with which to populate an array?

I am under the assumption that this would be a better solution, the less queries the better (I am not CMS savvy).

robert castelo’s picture

I do this so often I created a function for it:

function enewsletter_get_db_rows($query) {
  
  $results = db_query($query);
  $row_count = db_num_rows($results);
  
  for ($counter = 1; $counter <=  $row_count; $counter++) {
    $rows[] = db_fetch_object ($results);
  }

  return $rows;
}

You could also adapt the code for more complex queries by swapping out "db_query($query)" with your actual query.

Hope this helps

[a.k.a. MegaGrunt]

------------------------------------------
Drupal Specialists: Consulting, Development & Training

Robert Castelo, CTO
Code Positive
London, United Kingdom
----

Nooby-1’s picture

Thanks, this is good re-assurance that I'm on track, we've applied the same method to populating the array.

killes@www.drop.org’s picture

We do this all the time in Drupal.We use the shorter and more elegant while loop though...

$result = db_query($query);
while ($res2 = db_fetch_object($result)) {

}

--
If you have troubles with a particular contrib project, please consider to file a support request. Thanks.

nintern’s picture

I've tried to place this in my website and replace $query with my query(that has worked before) and nothing displays