I am intermittently seeing a problem when trying to select a row immediately after inserting it in PHP. This issue will only happen once in every 100-1000 occurances. This is using php 4.4, with no option to upgrade / be able to use PDO or mysqli. I was considering using transactions, but both queries execute and would continue to do so even with transactions, but the second query runs and returns empty RS so I doubt that transactions would hatch it.
As an example, take a table with two columns: an auto-increment counter, and a stored value. The value must be unique as well, but joins are made on the counter, not the value. Values can be entered by more than one user at a time, so I cannot simply trust the highest counter to give me the value I just inserted.
data:
data_id int(11) UNIQUE AUTO_INCREMENT NOT NULL
myData varchar(50) UNIQUE NOT NULL
Now each user is able to enter a new $val at any time, and when they enter it, an entry must also be made in the status table.
statuses:
status_id int(11) UNIQUE AUTO_INCREMENT NOT NULL
data_id int(11) NOT NULL
status int(1) NOT NULL
The code I'm using to accomplish this is:
// Get value
$insData = $_GET['VAL'];
// Insert value
$ins = mysql_query( "INSERT INTO data (myData) VALUES ('" . $insData . "')" )
or die(mysql_error());
// Get value's id
$res = mysql_query( "SELECT data_id FROM data WHERE myData='" . $insData . "'" )
or die(mysql_error());
// From here I would insert into the statuses table,
// but the new entry into the data table is sometimes not found!
Once every 100-1000 times the code gets run, the select will execute and return no rows. The data insert will execute correctly. I didn't believe that this was possible because the insert or die forces PHP to wait for a return value so that it would know whether or not to execute the 'or die' portion of the line. Is it possible that PHP has received a return value from the insert command before it has finished executing, thus the select statement immediately following the insert fails to return any rows? And how could this intermittent problem be prevented in the future?