I have a table with this columns : [user_id][game_id]
I need to close the game when two player join the game.
I used this code :
if(mysql_num_rows(mysql_query("SELECT user_id FROM live_games WHERE game_id = '$gid'"))<2){
mysql_query("INSERT INTO live_games (user_id, game_id) VALUES ('$uid', '$gid')");
echo "You have joined the game";
}else{
echo "Table is full";
}
the code will allow only two player to register but some times when there are too many users in the website , this condition will not work and three user will add in the table.
How can i fix?
You have a few options:
If using the InnoDB storage engine, perform a locking read with
SELECT ... FOR UPDATEwithin the same transaction as theINSERTstatement.Using PDO:
Change the table structure so that there are two columns,
player1andplayer2(initiallyNULL) and performUPDATE live_games SET player2 = ? WHERE game_id = ? AND player2 IS NULL, then check the number of affected rows; orChange the table structure so that there is an additional
playerNumbercolumn and then create a compositeUNQUEindex over(game_id, playerNumber).