Jump to content

Using last insert id in query


Kieran Menor

Recommended Posts

Here is my table:

 

TABLE `categories` (

  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,

  `name` varchar(255) NOT NULL,

  `order` int(10) unsigned NOT NULL,

  PRIMARY KEY (`id`)

)

 

Now, consider this query:

 

INSERT INTO `categories` (`name`, `order`) VALUES ('Test', ????)

 

I want the "order" field to have the same value as the ID field will get when the row is inserted. Is this possible?

 

Edit: And if so, how. :P

Link to comment
https://forums.phpfreaks.com/topic/168650-using-last-insert-id-in-query/
Share on other sites

This is my understanding:

 

LAST_INSERT_ID() & mysql_insert_id()

 

This 2 guys work on a connection basis.

 

If a host connects to MySQL and inserts a record, you can get the query ID using LAST_INSERT_ID() & mysql_insert_id() after executing the query.

 

If another hosts connects an execute LAST_INSERT_ID() & mysql_insert_id() will get 0, this is because no record has been inserted with this connection.

 

The only solution I can thing of to do what the OP wants, is to run a separate query or perhaps create a transaction.

 

Using two queries:

INSERT INTO `categories` (`name`) VALUES ('Test');

UPDATE `categories` SET `order`=LAST_INSERT_ID() WHERE Id=LAST_INSERT_ID();

 

Angel

 

 

 

The OP wants to do this:

 

INSERT INTO `categories` (`name`) VALUES ('Test');

UPDATE `categories` SET `order`=LAST_INSERT_ID() WHERE Id=LAST_INSERT_ID();

 

with a single query.

 

The only solution I can think of to achieve the final result that OP will get, is to run a separate query or perhaps create a transaction.  :'(

 

 

 

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.