2

I try to show a curve with energy produced for a day. So the curve must always be growing.

I try to increment the variable "energie_journ" my mysql database with all previous.

Exemple:

Mysql:

ID           energie_journ
1                 5
2                 5
3                 10
4                 6

Desired result:

First energie_journ = 1, the second = 10 (5 +5), third = 20 (5 +5 +10), fourth = 26 (5 +5 +10 +6).

Bit php:

while   ($row2  =   mysql_fetch_array($result2)) {
    extract($row2);

    $datetime *= 1000;

    $encode_energie_journ[] = array((float)$datetime, (float)$energie_journ == null ? null : (float)$energie_journ);
}

Thanks.

1
  • You should be adding each row value to an accumulator variable. Commented Jun 12, 2013 at 19:33

3 Answers 3

1

here you go i have made the sum of previous values in the query

SELECT id,(SELECT SUM(energie_journ) FROM `table` WHERE `id` <= p.`id`) AS  sum_col FROM `table` p

just use the result of sum_col which i thinks is as per your needs

hope this makes sense

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks ! I use your method, this is faster !
1

Try it like this:

$energy_journ = 0;
while   ($row = mysql_fetch_array($result2)) {
    $energy_journ += $row[1];
    // now save this value to an array, if that's what you are after.
}

And avoid using extract, it's going to give you headaches.

Comments

1

You can also have MySQL calculate this for you:

SELECT
  ID,
  energie_journ,
  @subtot := @subtot + val AS energie_journ_to_date
FROM myTable, (SELECT @subtot := 0) subtots
ORDER BY ID;

The result will look like this:

ID      energie_journ   energie_journ_to_date
 1             5                  5
 2             5                 10
 3            10                 20
 4             6                 26

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.