Sum Of Field In Database

In my head it seems simple but i can’t find anything anywhere that helps me out. Im looking for a code that will sit on the homepage of the website that does the following:

  1. Calcualte the SUM of all of one field in a database.
  2. Inserts this value into a text elemenet on my homepage.

Can anyone help?

Hi Tim

Check out this link, Yisreal helped me out with this a while back…

Tiaan

Hi Tiann,

Not having much look with this, i had a look at the link you posted and found the basis for the code but it is resulting as 0.

$w.onReady( function () {
//TODO: write your page related code here…
// no need to set the filter on the database since it’s still set
// how many items filtered in the dataset?
let count = $w(“#dataset1”).getTotalCount();

// get all of the items
$w(“#dataset1”).getItems(0, count)
.then((results) => {
let sumTotal = 0; // declare sum
let items = results.items;
items.forEach(item => {
// the amount is a string so convert
sumTotal = sumTotal + item.weekProfitLoss;
});
$w(“#text41”).text = “£439” + sumTotal;
}). catch ((err) => {
console.log(err);
});

});

Hi,
Do you get the items from the database? you can check that using " console.log ".
Maybe you need to run the code only after the dataset in ready, use the onReady event handler.

Let me know if you figured it out.
Good luck :slight_smile:

I’ve used to onReady function, how can I tell if the database is loading the results?

The onReady I mentioned refers the dataset, add

$w("#myDataset").onReady( () => {
});

after the “$w.onReady” and insert your code in the brackets.
To check the results you can implement this code after you get the items:

console.log(results.items);

Hi Tim

My apologies for the delay, I was out of action for a few days…

Or above is correct, if you’re running this in the pages’ onReady code then you will need to make sure the dataset has also finished loading.

If it still doesn’t work there are a few other things that might cause problems. Let me know!

Tiaan