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

Link to comment
Share on other sites

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
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

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