I am making a website in php, in which I want to sell some charge-numbers. For each request, I have to do these operations atomic:
- Asking database for an available charge-number
- marking the charge-number as sold
- increasing a number (in a file or database) which shows the number of clients got a charge-number
I know how to do these operations and if it may help, I am using mysql. But my problem is how to do these operations atomic between all request? I mean how can I force the web-server(apache) and php interpreter to run this part one by one for all request, not in a parallel manner?
P.s: Please make your answers as a solution by php, not a database related solution.
All of these operations are really database-dependent. So you don’t really need to make PHP run code in a critical section; it’s enough to serialize these operations at the database.
The simplest way to do that would be to
LOCK TABLES ... WRITEwhile you perform these; this guarantees that only one script would be talking to the database at once.Another approach would be to
SET TRANSACTION ISOLATION LEVEL SERIALIZABLEand run all operations in a transaction with autocommit turned off (you should really use a transaction to ensure data integrity even if you decide to go with the table lock though).Update: If you absolutely must do this in PHP, then you can achieve the goal using
flock:flockin exclusive mode will prevent any other process from locking the guard file and thus let your scripts execute strictly serialized, but please read the giant red warnings on the man page!