Search code examples
phpmysqlranking

Simple rating system in MySQL


Let's say I am running a small vote counter product. The values are stored in the database "content", with a row containing the amount of votes ("count"), I also have a row called "rank", how would I autosum these values so that I don't have to iterate through every single one in PHP, causing the script to slow down tremendously?


Solution

  • If you have a structure like this in a table

    item with fields: name, id, count, ...

    you can simply do:

    Up vote in the item with id = $id

    UPDATE item SET count = count + 1 WHERE id='$id';
    

    Down vote in the item with id = $id

    UPDATE item SET count = count - 1 WHERE id='$id';
    

    count will store the total number of votes.

    If you want to check for avoiding more than one vote per user/ip you should store each individual vote in another table and check this aditional table for non repeated votes before sending the previous queries.