chris
chris

Reputation: 36957

php mysql 5 star ratings structure

Ok, I know this isn't a unique concept. However the examples and tutorials I find don't really cover much they are all about this is what you do, upload it and done. Which to many extents is ok. However I want to build one from scratch.

What I have is a users who are voting on products and I am trying to figure out how to put the tables together properly to support this. So I have my users table, my product table, and from that I want to create 2 new tables. One thats actually the votes per product which will have a unique ID per product vote ranking so I can then have a second table that would have comments along with the votes. I could create on large table for the combination of the 2, yes.. but I foresee issues with that down the road as the table grows. So I would rather keep the 2 seperate. Another thing I want to do is keep tabs on the 10 different rank choices. 1/2 being the lowest 5 being the highest with total over all votes. So whats the best way to construct a table for at the least the rating storage per product.

That aside whats the best way to put the numbers in? decimals? whole numbers? how would I calculate the 5 star concept.

Upvotes: 1

Views: 1594

Answers (1)

nickf
nickf

Reputation: 546433

Three tables (two of which I assume you already have):

users (id, etc...)
products (id, etc...)

votes (userId, productId, rating, comments)

rating can be a SMALLINT type. This gives you a range of 0-255, and you could treat this as the user's score "times ten". eg: 4 stars = 40, 0.5 stars = 5. Unless you foresee users wanting to give something 3.1415 stars, that should be quite sufficient, plus more memory efficient than a float column.

Then, when you want to find the average score:

SELECT AVG(rating) FROM votes WHERE productId = xxx

I don't think that you should have any particular problems with a table structure like that. If you were being super-amazingly-paranoid, then yes, you could create a separate table for the comments, however, that would be the textbook definition of premature optimisation.

Upvotes: 4

Related Questions