Jump to content

[SOLVED] Assigning a new ID


almightyegg

Recommended Posts

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???

Link to comment
Share on other sites

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());

Link to comment
Share on other sites

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());

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.