1

What is wrong with this code?

$data455 = mysql_query("SELECT ROUND(SUM(gainloss), 4) FROM stats WHERE MONTH(date) = MONTH(CURRENT_TIMESTAMP) AND winloss = 'Win'");
$info455 = mysql_fetch_array($data455);
$testarray = array_sum($info455);
echo $testarray;

It does not display the correct sum. I want to get the sum of the last column where 'winloss' = 'win'

the output $testarray gives is 79.5843, but the correct sum is 41.6609.

Here is what my database looks like.

Database

1
  • You seem to be summing the column twice, once in the query and again in the php. Is that really what you want? Commented Sep 11, 2013 at 4:11

4 Answers 4

2

Try

mysql_fetch_assoc($data455);

Insted of

mysql_fetch_array($data455);

May this helps you because mysql_fetch_array returns both associative and indexing array you gets mixed result through it.

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

Comments

2

You don't have to use array_sum as in your query you already have the sum

$data455 = mysql_query("SELECT ROUND(SUM(gainloss), 4) AS total FROM stats WHERE MONTH(date) = MONTH(CURRENT_TIMESTAMP) AND winloss = 'Win'");
$info455 = mysql_fetch_array($data455);
echo $info455['total']; //this should give you the desired result

Comments

1

mysql_fetch_array by default returns the data from mysql as a numeric and associative array. You are essentially doubling your value by doing this. Change to mysql_fetch_assoc() and see what your result is.

http://php.net/manual/en/function.mysql-fetch-array.php

Comments

1

It is looks a problem of array sum. Looking at your SQL and the code line after that

$info455 = mysql_fetch_array($data455);

variable $info455 contains array something like

$info455['ROUND(SUM(gainloss), 4)'] = <some value>
$info455[0] = <some value>    

So here your variable only holding one value twice. so array_sum will double the value. First try to see your SQL is giving the correct result and how many rows. If you want multiple rows from SQL and then sum using PHP then you have to iterate on the resultset

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.