Forums

Sum of money

NabiXL 04 Dec, 2018
I am having a problem with a piece of code and its result.I have a list of prices on my table and i want the sum to be displayed at the bottom but the problem is that, i am not able to get the correct sum. Here is the code; and i uploaded the result also

<?php
$db =& JFactory::getDBO();
$query = "SELECT CONCAT('P', format(SUM(`price`),2)) AS `total_price`FROM `#expenditure`";
$db->setQuery($query);
$total_price = $db->loadResult();
echo "<strong>";
echo "Total Cost:";
echo $total_price;
echo "</strong>";
?>

healyhatman 04 Dec, 2018
OK so first of all why are you doing it in PHP instead of just using a read data action, and secondly why are you using concat and multiple echos instead of just
echo "<strong>Total Cost: </strong>P$total_price</strong>";
and thirdly no idea🙂 What happens if your remove all the Concat stuff out of interest
NabiXL 04 Dec, 2018
I am a newbie in PHP, Please help if there is a shortcut of doing it. I wrote this code at the footer of the table..see image. I will reduce it.
NabiXL 04 Dec, 2018
I am using CONCAT to add "P" as the currecy symbol to the price
NabiXL 04 Dec, 2018
Code simplified; Is there a simple way of doing it..
<?php
$db =& JFactory::getDBO();
$query = "SELECT SUM(`price`) AS `total_price`FROM `#expenditure`";
$db->setQuery($query);
$total_price = $db->loadResult();

echo "<strong>Total Cost: </strong>P$total_price</strong>"
?>
healyhatman 04 Dec, 2018
Is this in CCv6 or CCv5?

And I don't know why it would be giving you the wrong figure. What comes up if you just list the price field without SUMming? Just to make sure it's returning the right values
NabiXL 04 Dec, 2018
Its CCv5, so the data type of Price is VARCHAR in my MyPHPAdmin. Can this affect the results? C/z when i run the query there, it gives me the same result which is "21"
healyhatman 04 Dec, 2018
1 Likes
You will need to cast it to a number first.
NabiXL 04 Dec, 2018
Sorry it gives the same result as 21, without summing it gives me "2" the first digit of the first price.
This topic is locked and no more replies can be posted.