简体   繁体   中英

php mysql conditionally inserting row to different tables

I am inserting a row in two different tables depending upon a condition.

Let say, we have table named stories with 2 fields under consideration:
( story_id and comments_count )

and 2 other tables:

  1. regcomments (comment_id, story_id, comment_text)
  2. unregcomments (comment_id, story_id, comment_text)

Now, before inserting any new comment for any story_id , I just want to check if comments_count is less than 100. If so, the row should be inserted into regcomments , otherwise, the row should be inserted into unregcomments .

Here is the pseudo-code of how I've done that:

select comments_count from stories where story_id = x
if comment_count<100
    insert into regcomments
else
    insert into unregcomments

Now all what I am concerned about is if multiple users are accessing this script, Is there any chance this will fail? For example a story has 99 comments. 2 users call this function exactly at the same time. The first select query executes at the same time for both, and they both get 99. so both inserts will be made to regcomments, making count of regcomments 101, which is against my business rule. Any one has any idea, how the thing go. Or any ideas about how should I handle this scenario. (Don't ask me why I am using 2 tables :P anyway)

Yes, it can/will fail because 10 request may all receive 99 comments_count from the SQL query, and each time new row will be inserted to regcomments, and then you'll have 109 rows in the table.

One possible solution would be to move the checking logic into the SQL (use stored procedure with locking/mutex).

Use the InnoDB engine for the table and wrap the whole operation in a transaction. InnoDB will take care of the concurrency for you. Just prepare your code to handle an error from the insert/update statement. I guess you have to set a high isolation level to make sure the select does not run while the other operation is in progress. If this does not work you might need to use LOCK TABLE. Ugly but will do the job.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM