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 Quote Link to comment 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, Quote Link to comment 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. Quote Link to comment 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. Quote Link to comment 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 Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.