Adding numbers (math)

4 posts by 2 authors in: Forums > CMS Builder
Last Post: October 11, 2011   (RSS)

I have a listing that has a field for cost.
I need a script that will add up ALL cost fields and give a TOTAL.

Re: [s2smedia] Adding numbers (math)

By Jason - October 11, 2011

Hi,

You may be looking for something like this:

<?php
$totalCost = 0.00;
$listings = mysql_select('listings');

foreach ($listings as $listing) {
$totalCost += floatval($listing['cost']);
}

?>


This selects all the records form a section called "listings". It then loops through each record to total up the "cost" field and save it to a variable called $totalCost.

Note that the use of the mysql_select() function will only work if you're using CMSB Version 2.08 or above.

Hope this helps get you started.
---------------------------------------------------
Jason Sauchuk - Project Manager
interactivetools.com

Hire me! Save time by getting our experts to help with your project.
http://www.interactivetools.com/consulting/

Re: [s2smedia] Adding numbers (math)

By Jason - October 11, 2011

Hi,

Try this code:

<?php
$totalCost = 0.00;

$tableName = "listings";
$listings = mysql_query_fetch_all_assoc("SELECT * FROM `{$TABLE_PREFIX}$tableName`");

foreach ($listings as $listing) {
$totalCost += floatval($listing['cost']);
}

?>

---------------------------------------------------
Jason Sauchuk - Project Manager
interactivetools.com

Hire me! Save time by getting our experts to help with your project.
http://www.interactivetools.com/consulting/