Jr.
Jr.

Reputation: 55

How to SELECT the total values from a column in MySQL?

Here's what I'm currently using:

$query = mysql_query(" SELECT vote_count FROM votes ");
while ($row = mysql_fetch_array($query)) {    
    $total_votes += $row['vote_count'];
}

echo $total_votes;

Is there a more concise way, perhaps in the query itself without having to use the while loop?

Upvotes: 5

Views: 5270

Answers (2)

bensiu
bensiu

Reputation: 25564

SELECT SUM( vote_count ) AS vote_summary FROM votes 

Upvotes: 0

codaddict
codaddict

Reputation: 455020

You can use the MySQL sum function and get the sum from MySQL itself:

SELECT sum(vote_count) AS vote_count_sum FROM votes

Fetch the single row that the query produces in $row and $row['vote_count_sum'] will have the total.

Upvotes: 6

Related Questions