Jump to content

Getting the current insert ID


Kryptix

Recommended Posts

I'm trying to automatically insert a new topic on a FluxBB forum but I'm running into problems.

 

INSERT INTO `posts` (`poster`, `poster_id`, `message`, `posted`, `topic_id`) VALUES ('RSCEmulation', 19821, 'Here's my post', UNIX_TIMESTAMP(), (SELECT MAX(`id`) + 1 FROM `topics`));

 

INSERT INTO `topics` (`poster`, `subject`, `posted`, `last_post`, `last_post_id`, `last_poster`, `forum_id`) VALUES ('RSCEmulation', 'Here's my topic', UNIX_TIMESTAMP(), UNIX_TIMESTAMP(), (SELECT MAX(`id`) FROM `posts`), 'RSCEmulation', 37);

 

Both `posts` and `topics` use each others ID (which is a primary key and automatically incremented) to link together. When inserting the entry I need to get the corresponding ID.

 

Someone in IRC said to use the above but it's not working, it works OK but if I delete a record the expected ID is 2 but the above returns 0 (and continues increasing the more rows that have been deleted).

 

I'm also writing this in Java so it would help if I don't use any PHP functions.

 

Cheers guys.

Link to comment
Share on other sites

You need three queries for that.

1. Insert a new topic - with no post information for time being

2. Insert a new post using LAST_INSERT_ID() to link it to topic

3. Update topic with post information.

 

And no: LAST_INSERT_ID() is not the same as MAX(id) (although it often gives same result).

See mysql_insert_id

 

[edit]

Just noticed you do this in Java :P

 

Anyway, Java probably has an eqivalent of PHP's mysql_insert_id() - what package do you use to connect to database?

Link to comment
Share on other sites

  • 1 month later...
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.