1
$query = $db->query("SELECT * FROM orders");

while ($row = mysql_fetch_array($query)) {
    $cost= array_sum($row['cost']);
}

This is not working, I want to to calculate the sum of all elements but I get this error:

Warning: array_sum() expects parameter 1 to be array, string given in C:\xampp\htdocs\falco\classes\controller.php on line 303

Any idea how to calculate all the elements coming from mysql?

Thank you for your time and help.

1
  • The reason your solution throws an error is that it appears that $row is an array (containing a single row from your table) and $row['cost'] is a single value. Also, you are attempting to sum a single row, therefore the result would be the value of the field cost. The answers provided below are reasonable options, especially the select sum(cost) from foo... mysql statement Commented May 18, 2011 at 21:13

5 Answers 5

2

Why not let MYSQL handle it?

$query = $db->query("SELECT orders.*,SUM(cost) as sum_cost FROM orders");

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

Comments

2

If its just a sum you want you can let the database do it for you:

 Select sum(cost) from orders

Comments

1

Try this:

$query = $db->query("SELECT * FROM orders");
$cost = 0;
while ($row = mysql_fetch_array($query)) {
    $cost += $row['cost'];
}

Or from mysql:

$query = $db->query("SELECT sum(`cost`) as `cost` FROM orders");
while ($row = mysql_fetch_array($query)) {
    $cost = $row['cost'];
}

Comments

1

this should work:

$query = $db->query("SELECT * FROM orders");

$cost = 0;
while ($row = mysql_fetch_array($query)) {
    $cost += $row['cost'];
}

or even better

$query = $db->query("SELECT SUM(cost) FROM orders");
list($cost) = mysql_fetch_row($query);

Comments

1

Really, it sounds like you just want the sum.

'SELECT SUM(cost) as sum_cost FROM ORDERS'

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.