Using PHP + MYSQL as an internal tool, the user has a user name. After logging on successfully, the user requests data from the server. The request data is characterized, the status0 data of a table in the database. The code is written as follows: {code ...} after the request is successful... using PHP + MYSQL as an internal tool, the user has a user name. After logging on to the server, the user requests data. The request data is characterized by a table in the database.
status = 0
The code is written like this:
'select * from dir where status = 0 limit 1'
After the request is successfulstatus
It is set to-1, but when a user initiates a request at the same time, the same data is often requested. How can this problem be solved quickly? Database lock? Urgent -- new people who have just been in contact with the web --
Reply content:
Using PHP + MYSQL as an internal tool, the user has a user name. After logging on to the server, the user requests data. The request data is characterized by a table in the database.status = 0
The code is written like this:
'select * from dir where status = 0 limit 1'
After the request is successfulstatus
It is set to-1, but when a user initiates a request at the same time, the same data is often requested. How can this problem be solved quickly? Database lock? Urgent -- new people who have just been in contact with the web --
Transactions
Apply the pessimistic lock for update to select
Show code
begin$id = select id from table where status=0 for update;xxxxxxTODO SOMETHINGxxxxxupdate table set status=1 where id=$id;commit
The "uncle" said a solution to support transaction engines (such as InnoDB), but there is no solution for MyISAM.
Since it is only a small tool used internally, let me have a simple idea:
If only one piece of data is available, update the data before processing. If the processing fails, roll back. For example
UPDATE 'dir' SET 'status' =-1 WHERE 'status' = 0 # if this condition is true, only one request will be updated successfully and 1 will be returned. If other requests are returned, 0 will fail to be updated. # Continue the original logic. If the original logic cannot be processed, Update status back to 0, which is similar to a lock.
If there is a large amount of data, the first request is first followed by a file lock (for example, write a xxx. and check whether the file lock exists before each request. If yes, cancel the request.