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
Just try using
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
Your array contains an object with one property called
balance_value
, so you would access that like this