I have developed a game which works with php and jquery through ajax.
Essentially, when a request is made to the server the server will create a new game if there is not already one open. My database table for the games looks as follows:
id | closed | time
Where closed will be set to 1 once a game is over, and time is the unix timestamp of when the game was created.
Now the important thing here is that at any given time there can only be 1 game with closed = 0 in the table.
To do this I am using the following php code
$query = "SELECT id FROM games WHERE closed = '0' LIMIT 1";
$result = $this->database->query($query);
if ($result->num_rows == 0) {
$query = "INSERT INTO games_roulette SET time = '".time()."'";
$result = $this->database->query($query);
return $this->database->insert_id;
} else {
return false;
}
The thing is occasionally 2 games will be created, I believe due to 2 requests being sent at the exact same time, as the time values are always the exact same when there are 2 games open.
Is there any way I can have 100% certainty that there will never be 2 games with closed = 0 in the table?