PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Saturday, January 8, 2022

[FIXED] MySQL SUM() Returns an Empty Array Instead of Decimal Value

 January 08, 2022     mysql, php, sum, wordpress     No comments   

Issue

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


Solution

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

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


Answered By - RiggsFolly
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing