Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get last inserted id from table MySQL [duplicate]

I am running 1 script in php for that I need last inserted id in subscription table. By using that id I want to make notification note for that subscription.

I used:

SELECT LAST_INSERT_ID() FROM subscription

I am getting 0 instead of real last inserted value.

like image 336
Ronak Patel Avatar asked Jan 02 '14 21:01

Ronak Patel


2 Answers

If you use php to connect to mysql you can use mysql_insert_id() to point to last inserted id.

Like this :

mysql_query("INSERT INTO mytable (1, 2, 3, 'blah')");
$last_id = mysql_insert_id();

See this : mysql_insert_id()

like image 117
Hamed Persia Avatar answered Oct 01 '22 01:10

Hamed Persia


LAST_INSERT_ID() returns the last id from a previous insert statement. If you want the most recently inserted record and are using Auto Increment Prime keys, you can use the code below:

SELECT MAX( id ) FROM subscription;

If you need to know what the NEXT id will be, you can get this from INFORMATION_SCHEMA

SELECT AUTO_INCREMENT FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'test'

mysql_insert_id

like image 27
Binary Alchemist Avatar answered Oct 01 '22 01:10

Binary Alchemist