I had a flash game; a user had many items; each item is a row in a table in the database with columns:
id - user_id - item_type_id - quantity
Each time the user gets an item, I perform a select on the database to check if the user already has a row of that item type. If it does not exist, then it is inserted, else increment the quantity and commit; everything always in a transaction.
Sometimes, when the game gets heavy traffic, duplicate item rows appear. Right now, I perform a select to check for duplicate rows to merge the quantities and delete the dupped row.
- How does this problem happen?
- How can I prevent the problem happening?
I am using MySQL.
You need to ensure that there is a unique constraint (index) on the column pair
user_idanditem_type_id. Otherwise, the system can allow duplicate entries, exactly as you found out.