I am trying to perform the below simple query:

$query = db_select('sage.USER', 'USER')
  ->fields('USER', array('USER_ID', 'OFFICE_ID'));
$result = $query->execute();

I would like to then pull out the 'office_id' that is returned by the query, which I have been told can be done with the following:

$office = $result->office_id;

However, when I do 'print_r($office)' or 'echo $office', it would seem the $office string is empty. The database is not empty and contains the appropriate values.

Could someone please how I can pull out the contents of a drupal 7 query?


execute() returns a resource you can iterate over in a foreach loop, e.g:

foreach ($result as $record) {
  $office_id = $record->office_id;

In your case you probably want to use the fetchObject() method to actually retrieve the first record returned from the query:

$result = $query->execute()->fetchObject();
$office = $result->office_id;
  • I am trying to do this in a Migrate class. If I do $result->execute()->fetchObject() I will only ever get the first office_id and that will be used for all my records. If I do $result->execute() and loop over the records with foreach, then only the last office_id will be used for all the records...is there a way I can make it so the office_ids are used in sequential order? – chlong Apr 13 '12 at 18:12
  • I'm not really familiar with custom Migrate classes, but going off the code in your other question it seems like you need to add a condition to your db query. Is the code for your class very long? It might be worth posting it in a new question so people can offer advice, it gets a bit tricky to debug code in the comments and editing the answer with stuff not relevant to the original question might make this thread lose its focus – Clive Apr 13 '12 at 18:24

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.