Prevent two users from editing the same data

Posted by Industrial on Stack Overflow See other posts from Stack Overflow or by Industrial
Published on 2010-05-07T22:18:07Z Indexed on 2010/05/07 22:28 UTC
Read the original article Hit count: 259

Hi everyone,

I have seen a feature in different web applications including Wordpress (not sure?) that warns a user if he/she opens an article/post/page/whatever from the database, while someone else is editing the same data simultaneously.

I would like to implement the same feature in my own application and I have given this a bit of thought. Is the following example a good practice on how to do this?

It goes a little something like this:

1) User A enters a the editing page for the mysterious article X. The database tableEvents is queried to make sure that no one else is editing the same page for the moment, which no one is by then. A token is then randomly being generated and is inserted into a database table called Events.

1) User B also want's to make updates to the article X. Now since our User A already is editing the article, the Events table is queried and looks like this:

|   timestamp   |   owner   |   Origin      |   token      |
------------------------------------------------------------
|   1273226321  |   User A  |   article-x   | uniqueid##   |

2) The timestamp is being checked. If it's valid and less than say 100 seconds old, a message appears and the user cannot make any changes to the requested article X:

Warning: User A is currently working with this article. In the meantime, editing cannot be done. Please do something else with your life.

3) If User A decides to go on and save his changes, the token is posted along with all other data to update the database, and toggles a query to delete the row with token uniqueid##. If he decides to do something else instead of committing his changes, the article X will still be available for editing in 100 seconds for User B

Let me know what you think about this approach!

Wish everyone a great weekend!

© Stack Overflow or respective owner

Related posts about editing

Related posts about mysql