Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL: LAST_INSERT_ID() returns 0

I've got this test table:

CREATE TABLE IF NOT EXISTS `test` (     `id` INT(10) AUTO_INCREMENT,     PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=4; 

inserting using either of these three

INSERT INTO `test` (`id`) VALUES (NULL); INSERT INTO `test` (`id`) VALUES (0); INSERT INTO `test` () VALUES (); 

and issuing

SELECT LAST_INSERT_ID(); 

but the query always results in 0.

PHP's mysql_insert_id and PDO::lastInsertId() yield no result either.

I've been toying with this whole day and can't get it to work. Ideas?

like image 739
dwelle Avatar asked Dec 14 '12 14:12

dwelle


People also ask

What does the function LAST_INSERT_ID?

The LAST_INSERT_ID() function returns the AUTO_INCREMENT id of the last row that has been inserted or updated in a table.

What will be the value of LAST_INSERT_ID () for the newly created table?

With no argument, LAST_INSERT_ID() returns a 64-bit value representing the first automatically generated value successfully inserted for an AUTO_INCREMENT column as a result of the most recently executed INSERT statement.

Is MySQL LAST_INSERT_ID reliable?

This behavior ensures that each client can retrieve its own ID without concern for the activity of other clients, and without the need for locks or transactions. and even go so far as to say: Using LAST_INSERT_ID() and AUTO_INCREMENT columns simultaneously from multiple clients is perfectly valid.

How do I get the last inserted id in MySQL?

If you are AUTO_INCREMENT with column, then you can use last_insert_id() method. This method gets the ID of the last inserted record in MySQL.


2 Answers

The problem seemed to be in MySQL's phpmyadmin config file PersistentConnections set to FALSE which resulted in a new CONNECTION_ID every time a query was issued - therefore rendering SELECT LAST_INSERT_ID() ineffective.

more info in the subsequent topic Every query creates a new CONNECTION_ID()

Also thanks dnagirl for help

like image 192
dwelle Avatar answered Sep 20 '22 12:09

dwelle


Just my 50 cents for this issue, I simply noticed that you won't get a LAST_INSERT_ID greater than 0 if your table has no AUTO_INCREMENT set to an index.

I wasted about half hour on this. Turns out I keep getting a LAST_INSERT_ID() of 0, which for this table is actually ok.

like image 31
Ted Avatar answered Sep 22 '22 12:09

Ted