When I use the code below, I get the following error:

Call to a member function addExpression() on a non-object

 $query = db_select('node', 'n')
    ->fields('n', array('nid'))
  $query->addExpression('MAX(nid)', 'max_nid');

What is wrong with that code?

  • You added the addExpression after doing the query. It's not correct. You should add before that.
    – Stone Vo
    Aug 14, 2013 at 5:19
  • Where should I add the addExpression is it before fields() ? I have read that addExpression cannot be chained?
    – harshal
    Aug 14, 2013 at 5:21
  • After fields(). Can you try the code my answer. The format code in the comment block doesn't look good. So i must input in the answer
    – Stone Vo
    Aug 14, 2013 at 5:23

1 Answer 1


Change the code to the following one.

$query = db_select('node', 'n');
$query->fields('n', array('nid'));
$query->addExpression('MAX(nid)', 'max_nid');

The value returned from fetchAssoc() is an array. Since you are assigning the value returned from fetchAssoc() to $query, and then calling $query->addExpression(), you rightly get the error. You cannot call a method on something that is not an object (in this case, an array).

If you want to list all the node IDs and set max_nid to the maximum value, you can use the following code.

$query = db_select('node', 'n');
$query->fields('n', array('nid','type'));
$query->leftJoin('node', 'n1', 'n1.type = n.type');
$query->addExpression('MAX(n1.nid)', 'max_nid');
$result = $query->execute()->fetchAll();
  • I got the following error while trying to use the above code.Call to a member function execute() on a non-object
    – harshal
    Aug 14, 2013 at 5:25
  • Please try again
    – Stone Vo
    Aug 14, 2013 at 5:29
  • Sorry now its working but i am not able to get the value for MAX(nid).Do we need to write something else to get the value
    – harshal
    Aug 14, 2013 at 5:37
  • Please check the update of my answer
    – Stone Vo
    Aug 14, 2013 at 6:35
  • So I would have to write $query->execute()->fetchAssoc(); only at the variable where I need get the data..
    – harshal
    Aug 14, 2013 at 6:46

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.