1

I want to get the sum of the values in a column I ten print. I am executing the PHP code in the /devel/php page from the Devel module.

The query I want to execute is SELECT SUM(column_name) FROM table_name.

I tried the following code, but I get a Call to undefined function db_result() error.

$val = db_result(db_query('SELECT SUM(column_name) FROM {table_name}'));
print $val;

I also tried the following code, but I get a Object of class DatabaseStatementBase could not be converted to string in eval() error.

$query = db_select('table_name');
$query->addExpression('sum(column_name)', 'total');
$result = $query->execute();
print $result;

If I do not print $result, it works and executes, but I want to print the value.

How can I achieve this?

1 Answer 1

0

The first error is caused from the fact that Drupal 7 doesn't define db_result() anymore; it was used from Drupal 6.

The second error is caused from $query->execute() that returns a DatabaseStatementBase object, which cannot be convert to a string. (Converting the object to a string is what PHP does when an object is passed to print.)

You should use code similar to the following.

$query = db_select('table_name');
$query->addExpression('SUM(column_name)', 'total');
$result = $query->execute()->fetchField();

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.