almightyegg Posted February 21, 2009 Share Posted February 21, 2009 I wat to create 2 tables in the same page, they are connect so that the ID of table 1 is a foreign key in table 2 Because of this I need to code the new id in rather than auto_increment so I can place it in the table 2 when creating it. I've tried to do this: $maxid = mysql_query("SELECT max(id) FROM log"); $newid = $maxid+1; $insert = mysql_query("INSERT INTO log (`id`, `userid`) VALUES('$newid', '{$mem['id']}')") or die(mysql_error()); $insert2 = mysql_query("INSERT INTO fishlog (`fish`, `logid`) VALUES('{$fish['code']}', '$newid')") or die(mysql_error()); Only problem is $newid is always 16? Despite it being the first row it's 16.... then the second time it says multipul value of 16, so what do I do??? Quote Link to comment Share on other sites More sharing options...
GingerRobot Posted February 21, 2009 Share Posted February 21, 2009 That's not a good method. If you have simultaneous requests to this page, there's no guarantee that after selecting the maximum id and adding one, another record wont be inserted by another request before this request does the insertion. You should use mysql_insert_id to prevent this. Quote Link to comment Share on other sites More sharing options...
almightyegg Posted February 21, 2009 Author Share Posted February 21, 2009 Hmm... well it inserts correctly into one table (table 1) but it has a 0 value in table 2.... $newid = mysql_insert_id(); $insert = mysql_query("INSERT INTO log (`id`, `userid`) VALUES('$newid', '{$mem['id']}')") or die(mysql_error()); $insert2 = mysql_query("INSERT INTO fishlog (`fish`, `logid`) VALUES('{$fish['code']}', '$newid')") or die(mysql_error()); Quote Link to comment Share on other sites More sharing options...
GingerRobot Posted February 21, 2009 Share Posted February 21, 2009 You need to call mysql_insert_id() after inserting - the description of the function does say "Get the ID generated from the previous INSERT operation". For example: $insert = mysql_query("INSERT INTO log (`userid`) VALUES('{$mem['id']}')") or die(mysql_error()); $newid = mysql_insert_id(); $insert2 = mysql_query("INSERT INTO fishlog (`fish`, `logid`) VALUES('{$fish['code']}', '$newid')") or die(mysql_error()); Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.