1

Let's say I have 5 different columns, a, b, c, d, e, and I'm selecting multiple rows:

$result = mysqli_query($conn,"SELECT a,b,c,d,e FROM posts WHERE submitter='$user'");

while ($row = mysqli_fetch_assoc($result)){
  $ratings[] = $row; 
}

Example:

The user has 3 posts, so it'll select 3 rows in the query.

I want to sum all of the rows' values for a (and the rest of course).

e.g.

row 1 a value = 4

row 2 a value = 10

row 3 a value = 1

So I need to sum all of those to get 15.


I know to use array_sum($ratings) to find the sum of the array but only if you select one column (a) which can have multiple rows, but this is multi-dimensional right due to multiple column values being selected?

potashin
  • 44,205
  • 11
  • 83
  • 107
frosty
  • 2,779
  • 6
  • 34
  • 63
  • possible duplicate of [MySQL Sum() multiple columns](http://stackoverflow.com/questions/22369336/mysql-sum-multiple-columns) – Blue Jun 14 '15 at 06:45

2 Answers2

0

You can just use sum in your query:

select sum(a)
     , sum(b)
     , sum(c)
     , sum(d)
     , sum(e)
from posts
where submitter = '$user'
potashin
  • 44,205
  • 11
  • 83
  • 107
0

You can use count aggregate function and group by in MySQL.

SELECT
  submitter,
  count(a) as rating
FROM posts
WHERE submitter='$user'
GROUP BY submitter

A a result you will get something like that:

some submitter, 3
another submitter, 10
one more submitter, 1

Is this helpful?

enrico.bacis
  • 30,497
  • 10
  • 86
  • 115
Aleksei Akireikin
  • 1,999
  • 17
  • 22