Jump to content

Recommended Posts

I have a table with "votes" column. I basically want to retrieve the sum of all the votes columns associated with a user.

This is the full code. It gives me "NULL" output.

$count_votes = $db->prepare("SELECT SUM(votes) as total FROM entries WHERE user_id = :user_id");
$count_votes->bindParam(':user_id', $user_id);
$count_votes->execute();
$t_votes = $count_votes->fetchColumn();
$get_votes = $t_votes['total'];

echo $get_votes;

 

But if I remove the user_id bind paramter, it gives me the results. But I need that parameter to show which user has how many votes.

$count_votes = $db->prepare("SELECT SUM(votes) as total FROM entries");
$count_votes->execute();
$t_votes = $count_votes->fetchColumn();
$get_votes = $t_votes['total'];

echo $get_votes;

 

What am I doing wrong?

I find it difficult to believe that either of those code snippets work.

If you are using fetchColumn() the total that you want will be in $t_votes. (It will not be an array, just the value from the fetched column)

41 minutes ago, Barand said:

I find it difficult to believe that either of those code snippets work.

If you are using fetchColumn() the total that you want will be in $t_votes. (It will not be an array, just the value from the fetched column)

I just realized what the issue was. The votes in the table have a different user_id than what I am currently logged in as. So naturally it will not return any results. 

Here's a new code based on your suggestion. Works fine.

$count_votes = $db->prepare("SELECT SUM(votes) FROM entries WHERE user_id = :user_id");
$count_votes->bindParam(':user_id', $user_id);
$count_votes->execute();
$get_votes = $count_votes->fetchColumn();

 

19 hours ago, imgrooot said:

I want to retrieve the sum of all the votes columns associated with a user.

This is the full code. It gives me "NULL" output.

If the user has never voted, then all of the individual votes values will be NULL. 

If all of the values given to SUM() are NULL, then the result is also NULL.  

You may want to add code to your query to handle this case.  I think ...

IFNULL( SUM( votes ), 0 )

... will do what you want. 

Regards, 
   Phill  W.

  • Like 1
This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.