skip to Main Content

I get an empty array when trying to get the sum of payments in decimal type column (4,2). Here’s the code:

global $wpdb;
$balance = $wpdb->get_results("SELECT cast(sum(cpi) as decimal(5,2)) AS balance_value FROM hp_callbacks");
$row = mysqli_fetch_assoc($balance);
$sum = $row['balance_value'];
echo "Result: $sum";

When checking $balance I can see it’s an array:

global $wpdb;
$balance = $wpdb->get_results("SELECT cast(sum(cpi) as decimal(5,2)) AS balance_value FROM hp_callbacks");
echo "Result: $balance";

The output is:

Result: Array

I want to show up total balance for all rows in "cpi" column (no empty rows) as $sum. What am doing wrong? Any ideas to fix my code?
P.S. Using it in WordPress if it would be useful info…

2

Answers


  1. Just try using

    $rownum = 0 /* put the value of the row which you want to retrieve, I want to retrieve only the first row */ 
    $balance[$rownum][0]
    

    The problem is caused as your code returns an array, which cannot be printed using echo. If you want to to print the array use

    print_r($balance);
    
    Login or Signup to reply.
  2. Your array contains an object with one property called balance_value, so you would access that like this

    echo "Result: " . $balance[0]->balance_value;
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search