Michael Tichoň
Michael Tichoň

Reputation: 291

PHP/MySQL multiple votes

Hello I have voting system on my website but I would like to disable multiple voting from users. If the user votes he/she cannot vote again. Here is one solution which I have but is not good imo.

I created a column in users table: users_avoted where I would store the IDs of articles which he/she voted like tihs:

1|2|5|6 

From this I would be able to check whether the user had already voted. But the thing is there will be a lot of articles so VARCHAR(255) will not be enough to store all of those IDs. Any other solutions?

Thanks

Upvotes: 1

Views: 195

Answers (3)

Scotch
Scotch

Reputation: 3226

Don't denormalize it like that. Just have a two column table, userVotes, with a composite Key for UserID and ArticleID.

example data:

  userid  | articleid
   1          1
   1          2
   1          67
   2          1

This is better than something like

  userID    | articleID
    1         1,2,67

Which is what it looks like you are suggesting. Please don't do this, and keep it normalized unless you want to do gymnastics every time you query. To elaborate, implementing what you suggested would defeat the purpose of using a RDBMS, in order to 'cheat' on one specific query.

Upvotes: 5

chriz
chriz

Reputation: 1580

Store the votes in a table layed out like: id,username,voteid,vote for example.

Then when the user votes, check that table for matching rows.

For example:

if ($username == $dbusername && $voteid == $dbvoteid){
     $disallowed = true;
}

Upvotes: 0

crush
crush

Reputation: 17023

You could instead make a table like:

users_avoted {
    article_id,
    user_id,
    answer_id
}

Make a unique index out of article_id and user_id. That would only allow a single record to be input for that.

So, say they choose option 5 on article 2, and they are user 1.

Now, when you attempt to insert into the table:

INSERT INTO users_avoted VALUES (2, 1, 5)

You can't because the user already voted.


The benefit of this approach is that you don't have to check if they voted already first.

Upvotes: 0

Related Questions