Good evening.
I have a doubt about inclusion in the database. A common example is a user account where the user names must be unique.
In the following logic:
Example:
<?php
$username = $_POST['username'];
$query = "SELECT * FROM `user_tbl` WHERE `username` = '{$username}'";
$result = mysql_query($query);
if ( mysql_num_rows ( $result ) > 1 ) {
/* Username already exists */
echo 'Username already exists';
} else {
/* Username doesn't exist */
/* a certain time is elapsed after checking */
/* .. insert query */
}
My question is, in a system with high volume of requests, it is possible that between the time to check whether the user name already exists and the inclusion (if the user name does not exist), another user can do the same action in same time?
UPDATE
I know about the safety issue, use this code (copy and past) to explain to the question is about the possibility of two users do the same thing at the same time. On the issue of unique index, I know how it works, maybe I was not clear on the question, it was only to see if there was a possibility of "simultaneous commands occur." Thanks for the answers.
Besides the already placed correct comments, the solution to this is to use transactions & an unique index:
The unique index guarantees that a value can only exist once.
In your case the index could be:
CREATE UNIQUE INDEX idx_nn_1 ON user_tbl(username);
That way the user can only exist once. If two people insert the same username now at the same time, one of the inserts will fail. That failure you need to catch and handle.