I am trying the following

global $wpdb;
$sum = $wpdb->get_var("select sum(first), sum(second) from table where id > 1");

I am unable to get the values from each request. I have tried

echo $test->sum(first);

I have tried to change the sql statement to include AS

 $sum = $wpdb->get_var("select sum(first) as firstRequest, sum(second) as secondRequestfrom table where id > 1");

echo $test['firstRequest'];

I have tried a foreach statement

foreach($test as $tester){
  echo $tester['sum(first')];


foreach($test as $tester){
  echo $tester['firstRequest'];

How can I retrieve the sum of multiple rows from a single get_var statement? If not possible, and I need the sum of 5 different rows, would I have to create 5 separate get_var statements? Would this decrease the querying speed, if so, is it even noticeable?

  • why not get_results instead?
    – Milo
    May 18 '14 at 0:48
  • @milo - from my understanding of wordpress, since I am looking to return a value, I should use the get_var. I think I tried get_results as well, then tried to iterate though with a foreach statement with no luck. May 18 '14 at 0:51
  • get_results along with an AS in the sql statement and a foreach statement combined worked to accomplish what I was looking for. Thank you! May 18 '14 at 0:59
  • 3
    add your code as an answer and accept it so it may help others in the future.
    – Milo
    May 18 '14 at 1:03

$wpdb->get_var will do exactly what the name suggests-- return a single value. So this:

$sum = $wpdb->get_var("select sum(first), sum(second) from sums_test where id > 1");

Will return the result of sum(first). The rest of the result is lost (though cached I believe).

The method you want is get_row which will return a complete row of results.

$sum = $wpdb->get_row("select sum(first) as first_sum, sum(second) as second_sum from sums_test where id > 1");

I have added AS clauses as well to make it easier to use the data in PHP. You can now get your results with $sum->first_sum), $sum->second_sum, and so on for as many as you retrieve, or you may use something something more dynamic like:

foreach ($sum as $k=>$v) {
  echo $k.' -> '.$v.'<br>';
  • Thanks for the answer! I ended up using get_results instead of get_row along with an AS clause. It seems to produce the same result. Thank you for the dynamic foreach statement! I hadn't thought of a way to write it as good. Thanks again! May 19 '14 at 1:54

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.