Schraalhans Keukenmeester wrote:Race condition? If user 1 increments the $msgid and user 2 selects> X-Followup: comp.lang.php
> I have a PHP script that adds messages to a simple MySQL Database.
> (PHP 5.0.3, MySQL 4.1.1)
> One of the fields it stores is msgid.
> The new msgid is a count of all current msgs in the db plus one
> $query = 'select count(*) from messagesdb;';
> $result = mysql_query ($query, $conn);
> $msgid = mysql_result ($result, 'count(*)') + 1;
> The next message is added using the above msgid.
> For some reason (there are NO other scripts/systems accessing this
> table, it is all on a local testmachine) I now have about 200 messages
> in the system, but some id's occur more than once, up to 4 times.
> I cannot explain this behaviour. I know I could avoid the entire issue
> by autonumbering the messages, but still there is something funny going on.
> I am wondering, is php messing up, or is this a mysql glitch, or am I
> missing something here ?
count(*) before user 1 has added her message -> duplicate entries for
this $msgid. You can avoid this by putting a unique constraint on your
message ID. Which you should have done anyway ... Or using transactions.
Or autoincrement. Or you could, of course, re-invent other wheels.