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?

1

2 Answers 2

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'
Sign up to request clarification or add additional context in comments.

8 Comments

What will be stored in the $ratings array?
I think you read that wrong.. -What- will be stored in there I mean?
@frosty: sorry, there will be an array of sums for each column, you can var_dump result to see it yourself.
Thanks, I think it's still producing a multi-dimensional array tho. array(1) { [0]=> array(5) { ["sum(a)"]=> string(2) "22" --- how do I retrieve the "22"?
Yes, just saw your edit. Was trying $row[0] and $row['a'] but wasn't working, $row['sum(a)'] works though
|
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?

1 Comment

ty for the answer, I was able to get it working with the other answer tho

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.