Access last inserted row in mysql

On my db server, I insert data into a table with an auto-increment field, such as "id". Now I want to use the value of this last inserted "id" in the next steps. I can use this: -

select * from table_name order by id desc limit 1; 

But the problem is that this is a server, and many other insertions can occur, and there may be a case when I try to get data with the request I specified and get a different identifier, i.e. there may be some other insertion between my insert and the choice, and I will not get the value that I inserted. Any way that this could be resolved.

Thanks in advance.

+7
source share
6 answers

Use this

 mysql_insert_id(&mysql); 

since its basic structure

 mysql_insert_id ([ resource $link_identifier = NULL ] ) 

Gets the identifier generated for the AUTO_INCREMENT column by the previous query (usually INSERT).

or in mysql use

  SELECT LAST_INSERT_ID(); 

here ref links

http://dev.mysql.com/doc/refman/5.0/en/getting-unique-id.html

http://php.net/manual/en/function.mysql-insert-id.php

+7
source

Use this mysql_insert_id ()

It returns the AUTO_INCREMENT identifier generated from the previous INSERT operation.

This function returns 0 if the previous operation did not generate the AUTO_INCREMENT identifier, or FALSE if the MySQL connection failed.

+4
source

call the LAST_INSERT_ID() function immediately after insertion and save somewhere.

+3
source

try it

 SELECT LAST_INSERT_ID(colid) From tablename; 

heres Link

+2
source

you can get the identifier if you call the LAST_INSERT_ID () function immediately after insertion, and then you can use it.

+2
source

For any last inserted record, it will go through mysql_insert_id (). If your table contains any AUTO_INCREMENT column, it will return this value.

 mysql_query("INSERT INTO test(emsg,etime) values ('inserted',now())"); printf("Last inserted record has id %d\n", mysql_insert_id()); $last_id=mysql_insert_id(); echo $last_id; ?> 
+1
source

All Articles