简体   繁体   中英

How can I use concurrent access of mysql table in PHP

I have two Php files (a.php, b.php). In a.php I'm retrieving a value from a table and displaying it in PHP and sending it to b.php. In b.php, I'm incrementing that value by 1 and updating it on the table, (but b.php will take more time because of many operations). Now the problem is when performing the operation in b.php, if I clicked a.php for another task, I need to get the incremented value to display in a.php, but it will show only the previous value, because the b.php is not fully executed. Help me to solve this issue.

An INSERT , UPDATE , or DELETE operation locks the relevant tables [myISAM] or rows [InnoDB] until the operation completes. If a SELECT comes in trying to read a locked object it will wait for the operation to complete.

It's worth noting that unless your server is horrendously overloaded, or your INSERT / UPDATE / DELETE operations number in the many thousands of rows, or both, you will not even notice the wait.

In short: don't even bother worrying about what you've described.

You are describing a race condition. If script A must wait for all operations of script B to complete in order to assure proper meaning of the count column then you must block script A through table locks (this is true whether the engine is MyIsam or InnoDB). However, if script A does not need to wait for all operations of B to finish to give proper meaning to the count column (ie, only waiting for the increment operation is necessary), then you need to do nothing special.

Having said that, script A is probably not what you need to worry about. It's more likely that other invocations of script B needing to increment the count column will create your race conditions. Ensure you are performing your increment through SQL code rather than pulling the value into PHP and then resaving to the database.

Finally, you'll want to make sure you're not creating an aggregate column for no reason. If the count column is merely the number of rows that meet a certain set of criteria, just use the query instead of creating a column that holds the count (aggregate columns/tables should only be used for caching efforts when profiling shows it's necessary and should be clearly named to denote this).

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