bri4n Posted September 25, 2007 Share Posted September 25, 2007 Hi guys and gals! I'm a newbie to PHP and was wondering if someone can tell me how I can achieve the following. I have a column in my database that contains dollar values. Want I want to know is how I can use PHP to add up these values into one "Grandtotal" and then divide the result by 2. Thanks for any help and pointers! Thanx Link to comment https://forums.phpfreaks.com/topic/70598-solved-basic-php-math-query/ Share on other sites More sharing options...
hemlata Posted September 25, 2007 Share Posted September 25, 2007 Hello, Loop through the records array and start adding all dollar values into a single variable. See below code as example and after the loop, divide the variable value by 2 as per your requirements. <?php // Initialize local variable $grant_total = 0; // loop through records array while($row= mysql_fetch_array($result)) { // Add all the column values $grant_total += $row{'column_name'}; } // Check if total is not zero If (0 != $grant_total) { // Divide the found result by 2 to get the required result $total = $grant_total/2; } ?> Hope this will help you. Regards, Link to comment https://forums.phpfreaks.com/topic/70598-solved-basic-php-math-query/#findComment-354775 Share on other sites More sharing options...
steelmanronald06 Posted September 25, 2007 Share Posted September 25, 2007 Just an FYI. It might make it easier if you changed this line: If (0 != $grant_total) to: If ($grand_total > 1) Mainly because you would only want to divide by two if there is at least two dollar amounts in the system. Link to comment https://forums.phpfreaks.com/topic/70598-solved-basic-php-math-query/#findComment-354893 Share on other sites More sharing options...
cooldude832 Posted September 25, 2007 Share Posted September 25, 2007 even easier let mysql get you the sum right off the database (assuming you don't need the individual values) I believe you can say somethign like <?php $q = "select sum($field) from `Table` Where True"; ?> Replacing table, $field and True with your parameters and then that result is your summation, however if you need the individual item's prices then doing it the other way is much more practical as this would require 2 quires, or at least more data drawn than needed. Link to comment https://forums.phpfreaks.com/topic/70598-solved-basic-php-math-query/#findComment-354938 Share on other sites More sharing options...
bri4n Posted September 26, 2007 Author Share Posted September 26, 2007 Hi cooldude and sttelman! Thanks for your help, the code works beautifully! Thanx, Brian Link to comment https://forums.phpfreaks.com/topic/70598-solved-basic-php-math-query/#findComment-355502 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.