Jump to content

[SOLVED] Basic PHP Math Query


bri4n

Recommended Posts

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

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,

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. 

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. 

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.