1

I think I've got a race condition within a bit of PHP code whereby mysql_insert_id() is returning 0 - but I can't work out why.

$insertsess=mysql_query("insert into cior_sessions values ('','$cid','$uid','$tutook',STR_TO_DATE('$sessiondate','%d/%m/%Y'),'$sessionnum')");
$sessionid=mysql_insert_id($insertsess);
echo "<input type=\"hidden\" name=\"sid\" id=\"sid\" value=\"" . $sessionid . "\">";

I've not been able to replicate the problem myself, but can see that other users have (by virtue of the fact that what they're subsequently doing is resulting of an SID of 0, but not consistently).

My understanding of this was that mysql_insert_id would wait for the query from $insertsess to complete - is this wrong? If so, do I need to have something such as a watchdog loop which waits for mysql_insert_id to return something other than zero? That seems a bit stupid. :/

GarySmith
  • 11
  • 1
  • 1
    it was more than 20 minutes ago that this question had been asked, and nobody has posted the standard "please do not use deprecated `mysql_*` functions" comment yet :) – Alex Shesterov Sep 15 '13 at 10:37

1 Answers1

4

When you call mysql_insert_id() you should be using the connection resource, not the result set resource as you are doing in the snippet you posted.

$link = mysql_connect('dbhost', 'dbuser', 'dbpass', 'dbname');
$result = mysql_query("Some query here');
$lastId = mysql_insert_id($link); // you have used your result set here
MichaelK
  • 352
  • 4
  • 11
  • Ok - how does that work if multiple people are using the application concurrently? For instance, $link might have lots of concurrent users. – GarySmith Sep 15 '13 at 10:26
  • 2
    Each PHP thread will create a new link every time a new page is generated, and drop it when the page is done. Each thread serves only one user at a time, although it might serve many users so there's no sharing of the link –  Sep 15 '13 at 10:30
  • Aha, that makes sense. Lovely stuff - thanks for your help! I would upvote - alas, newby. Sorry. I'll try and remember to come back and upvote it when I'm able to! – GarySmith Sep 15 '13 at 10:46