Mc Filip
Mc Filip

Reputation: 19

Count all values from mysql

I am wondering how I can make this work, I tried:

$query = "SELECT author, SUM(likes) FROM posts WHERE author = '$usern' GROUP BY likes order by SUM(likes) + 0 desc"; 

$result = mysql_query($query) or die(mysql_error());

But it just gives me number of likes of first post, not from all posts in-one. So, I need to get all likes from all posts where username is $usern

Database rows: id, likes, author, date

I need to output one number, e.g. 50 if the author has 5 posts and on every post 10 likes

Upvotes: 0

Views: 31

Answers (2)

Dm3Ch
Dm3Ch

Reputation: 761

SELECT `author`, SUM(`likes`) FROM `posts` WHERE `author` = $user;

this query will show you how many likes have got $user under all his posts

Upvotes: 0

Glorfindel
Glorfindel

Reputation: 22631

If you really only want the total number of likes for $usern, this simple query will already suffice:

$query = "SELECT SUM(likes) FROM posts WHERE author = '$usern'";

You only need a GROUP BY only if you want to retrieve this information for multiple authors at once:

$query = "SELECT author, SUM(likes) FROM posts GROUP BY author ORDER BY SUM(likes) + 0 DESC"; 

Upvotes: 1

Related Questions