Home > Blockchain >  MySQL SUM() Returns an Empty Array Instead of Decimal Value
MySQL SUM() Returns an Empty Array Instead of Decimal Value

Time:12-16

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...

CodePudding user response:

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);

CodePudding user response:

Your array contains an object with one property called balance_value, so you would access that like this

echo "Result: " . $balance[0]->balance_value;
  • Related