Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get the last inserted ID of a MySQL table in PHP?

Tags:

php

mysql

I have a table into which new data is frequently inserted. I need to get the very last ID of the table. How can I do this?

Is it similar to SELECT MAX(id) FROM table?

like image 292
gweg Avatar asked Nov 06 '09 06:11

gweg


People also ask

How do I find the last id of a MySQL database?

How to get last inserted id of a MySQL table using LAST_INSERT_ID() We will be using the LAST_INSERT_ID() function to get the last inserted id. Last_insert_id() MySQL function returns the BIG UNSIGNED value for an insert statement on an auto_increment column.

How can I get the last inserted id from a table in SQL?

To get an ID of last inserted record, you can use this T-SQL: INSERT INTO Persons (FirstName) VALUES ('Joe'); SELECT ID AS LastID FROM Persons WHERE ID = @@Identity; You can use query like this inside stored procedure or as an ad-hoc query.

How can I get the last update id in MySQL?

mysqli_insert_id($link) will return exactly the id of last updated row. I am using this funtion in my projects for the same purpose. You can use it both in synchronous or asynchronous queries. Just insert $lastupdated_row_id = mysqli_insert_id($link) into your code and it will work for you.


2 Answers

If you're using PDO, use PDO::lastInsertId.

If you're using Mysqli, use mysqli::$insert_id.

If you're still using Mysql:

Please, don't use mysql_* functions in new code. They are no longer maintained and are officially deprecated. See the red box? Learn about prepared statements instead, and use PDO or MySQLi - this article will help you decide which. If you choose PDO, here is a good tutorial.

But if you have to, use mysql_insert_id.

like image 92
deceze Avatar answered Oct 06 '22 00:10

deceze


there is a function to know what was the last id inserted in the current connection

mysql_query('INSERT INTO FOO(a) VALUES(\'b\')'); $id = mysql_insert_id(); 

plus using max is a bad idea because it could lead to problems if your code is used at same time in two different sessions.

That function is called mysql_insert_id

like image 36
RageZ Avatar answered Oct 06 '22 01:10

RageZ