How to properly avoid Mysql Race Conditions

心已入冬 提交于 2019-11-30 21:32:18

To achieve this, you will need to lock the record somehow. Add a column LockedBy defaulting to 0.

When someone pushes the button execute a query resembling this:

UPDATE table SET LockedBy= WHERE LockedBy=0 and id=;

After the update verify the affected rows (in php mysql_affected_rows). If the value is 0 it means the query did not update anything because the LockedBy column is not 0 and thus locked by someone else.

Hope this helps

When you post a row, set the column to NULL, not 0.

Then when a user updates the row to make it their own, update it as follows:

UPDATE MyTable SET ownership = COALESCE(ownership, $my_user_id) WHERE id = ...

COALESCE() returns its first non-null argument. So even if you and I are updating concurrently, the first one to commit gets to set the value. The second one will not override that value.

You may consider Transactions

BEGING TRANSACTION;
SELECT ownership FROM ....; 
UPDATE table .....; // set the ownership if the table not owned yet
COMMIT;

and also you can ROLLBACK all the queries between the transaction if you caught an error !

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!