开发者

SUM of all rows from WHERE condition?

I'm trying to add the contents of all the rows retrieved from a query.

So far I have tried:

$totalque开发者_开发知识库ry = "SELECT SUM(catalogue.price) AS fCount
        FROM catalogue LEFT JOIN orders ON catalogue.plantid = orders.orderplantid
        WHERE orders.orderplantid = '$actualresult' AND orders.ordercustomerid = '$actualresult2' GROUP BY catalogue.price";
        $result3 = mysql_query($totalquery) or die ("Query failed : " . mysql_error());
        $totalresult = mysql_result($result3,0);

and then echoing out the $totalresult, but the problem is only displays the last value, rather than the sum of all of the values selected - any ideas on where I'm going wrong?


Remove GROUP BY catalogue.price from the end of the line; the sum command IS one of the aggregate functions.


If the grouping results in multiple groups being formed, you'd need to retrieve the rows in a loop:

while($row = mysql_fetch_assoc($result3)) {
    $total = $row['fCount'];
    ... do something with total ...
}

As it stands now, you're only fetching the first summed value and throwing away the rest.


most likely because there are multiple results instead of just one. and because you're not looping through the array and storing all values to view, all you're seeing is the last value of the result-set because it's the last assignment ot the $totalresult variable...

try mysql_fetch_assoc($result3) or mysql_fetch_array($result3) and loop through the results to get all returned information...


Try removing the GROUP BY statement.

Also, if $actualresult and $actualresult2 is input from the user, be sure to escape these to avoid SQL injection attacks:

$totalquery= "... WHERE orders.orderplantid = '" . mysql_real_escape_string($actualresult) . "' AND orders.ordercustomerid = '" . mysql_real_escape_string($actualresult2) . "'";


instead of mysql_result() use mysql_fetch_array()

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜