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
https://forums.phpfreaks.com/topic/195642-getting-the-current-insert-id/
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?

  • 1 month later...

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.