104

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?

TRiG
  • 10,148
  • 7
  • 57
  • 107
gweg
  • 2,820
  • 6
  • 23
  • 23
  • 1
    yes, you this query will return the last id of the table. But one condition is that ID must be Primary key. So you can avoid repentance. – sathish Nov 06 '09 at 06:52
  • 8
    @sathish: The main problem of that method is *concurrency*. – Christian C. Salvadó Nov 06 '09 at 07:02
  • 3
    To elaborate: The problem with it is that if somebody else inserts something into the table between your `INSERT` and query for `MAX(id)`, you may get an id that's not *your* last id. – deceze Nov 06 '09 at 07:07
  • We should tell the questioner that mysql_insert_id() provides the ID of the most recently inserted record, which is what I think he was really asking. – Ed Poor Feb 08 '12 at 19:15
  • 3
    @Jocelyn that question was asked a **year later** with thousands less views than this question. – Naftali Dec 28 '12 at 16:16
  • 3
    @Neal, you're right. The other question should be closed as duplicate of this one. – Jocelyn Dec 28 '12 at 16:20
  • @Neal I don't think question age matters. If it did they probably would have [implemented this](http://meta.stackexchange.com/q/12031/148672). However this one does have the better content so the reopen made sense. – Conrad Frix Dec 28 '12 at 21:19
  • All of the answers assume the program in question was the last to insert into the table. What if it wasn't? Is there anything better than "select max(id) from table"? Since, most likely, it's an autoincrement int, shouldn't the DB already have the last or next number ready? – Douglas Mauch May 01 '13 at 15:47
  • Actually, I found where you can get the AUTO_INCREMENT field from the information_schema.TABLES table for that schema and table. It works, but is actually drastically slower than the select max method, which is actually screaming fast. Even on a table with 2M+ rows. – Douglas Mauch May 01 '13 at 16:01
  • `MAX(id)` is so fast, because it is an index only-read. It just needs to read log(n) numbers form the index and won’t even open the table in question. For a 2M table that’s probably 21 memory reads. – Chronial Jul 01 '13 at 13:56
  • [[1]] [mysql_insert_id()][1] Thanks [1]: http://stackoverflow.com/questions/19383181/idea-for-writing-a-mysql-query – Krunal Shah Oct 18 '13 at 04:12
  • Use [mysql_insert_id()](http://php.net/manual/en/function.mysql-insert-id.php) function. See similar question [here](https://stackoverflow.com/questions/1674344/php-and-mysql-ids/) – NawaMan Nov 06 '09 at 06:52

16 Answers16

142

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.

Community
  • 1
  • 1
deceze
  • 510,633
  • 85
  • 743
  • 889
  • 1
    The problem with this one is if you have a lot of inserts happening (eg your database also logs something) you can get the wrong ID. – Mike May 04 '12 at 18:30
  • 1
    @Mike Not if you use `mysql_insert_id` *right after* your `mysql_query`. If of course you execute several other queries on the same connection in between, well, there's nothing that can help you there. – deceze May 05 '12 at 01:29
  • 7
    To garantee you will NEVER get a wrong id, wrap your code with a [TRANSACTION](http://stackoverflow.com/questions/2708237/php-mysql-transactions-examples). – Marcelo Assis Jun 22 '12 at 20:21
  • 30
    mysql makes sure this is the last id OF THE CURRENT CONNECTION, so there will be no problems if you put this statement right after the insert query. No worries about other processes doing inserts.No need to wrap this in a transaction. The mysql manual says: "The ID that was generated is maintained in the server on a per-connection basis. This means that the value returned by the function to a given client is the first AUTO_INCREMENT value generated for most recent statement affecting an AUTO_INCREMENT column by **that client**. This is the reason you should **not** use select MAX(ID) – woens Oct 04 '12 at 20:15
  • 1
    @deceze, What's with this `PDO` biasness we see everywhere? Let's look at the [feature comparison](http://php.net/manual/en/mysqlinfo.api.choosing.php#example-1642) again. It's clear that `mysqli` is the winner when you need to get your hands dirty with low level stuff. In other words, even if one chooses PDO, he *eventually* will need to use `mysqli` anyway. – Pacerier Jan 28 '15 at 11:44
  • And why is that @Pacerier ? – Naftali Jan 28 '15 at 11:45
  • @Neal, What do you mean? – Pacerier Jan 28 '15 at 11:49
  • Why if you are using pdo will you have to use mysqli?? @Pacerier – Naftali Jan 28 '15 at 11:51
  • @Neal, The rows in the feature comparison that say `Yes | No` and `Yes | Most`, e.g. *"API supports non-blocking, asynchronous queries with mysqlnd......."* – Pacerier Jan 28 '15 at 12:01
55

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

RageZ
  • 26,800
  • 12
  • 67
  • 76
26

With PDO:

$pdo->lastInsertId();

With Mysqli:

$mysqli->insert_id;

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.

Community
  • 1
  • 1
Naftali
  • 144,921
  • 39
  • 244
  • 303
  • [What's with this `PDO` biasness we........](http://stackoverflow.com/questions/1685860/how-do-i-get-the-last-inserted-id-of-a-mysql-table-in-php/1685867#comment44750082_1685867) – Pacerier Jan 28 '15 at 11:44
  • Very clear. I was actually using insert_id() which made me lose precious minutes. – cdsaenz Sep 22 '22 at 22:17
22

It's ok. Also you can use LAST_INSERT_ID()

x2.
  • 9,554
  • 6
  • 41
  • 62
8

What you wrote would get you the greatest id assuming they were unique and auto-incremented that would be fine assuming you are okay with inviting concurrency issues.
Since you're using MySQL as your database, there is the specific function LAST_INSERT_ID() which only works on the current connection that did the insert.
PHP offers a specific function for that too called mysql_insert_id.

dlamblin
  • 43,965
  • 20
  • 101
  • 140
8

Try this should work fine:

$link = mysqli_connect("localhost", "my_user", "my_password", "world");

$query = "INSERT blah blah blah...";
$result = mysqli_query($link, $query);

echo mysqli_insert_id($link);
Sandhu
  • 818
  • 9
  • 18
  • 1
    Thank you for noticing. I have edited the code, actually it is $link (variable holding the connection) – Sandhu Apr 05 '17 at 09:43
4

Clean and Simple -

$selectquery="SELECT id FROM tableName ORDER BY id DESC LIMIT 1";
$result = $mysqli->query($selectquery);
$row = $result->fetch_assoc();
echo $row['id'];
Hitesh
  • 109
  • 7
3

It's ok to use mysql_insert_id(), but there is one specific note about using it, you must call it after executed INSERT query, means in the same script session. If you use it otherwise it wouldn't work correctly.

Jonas Czech
  • 12,018
  • 6
  • 44
  • 65
Mihail Dimitrov
  • 574
  • 3
  • 9
3

To get last inserted id in codeigniter After executing insert query just use one function called insert_id() on database, it will return last inserted id

Ex:

$this->db->insert('mytable',$data);
echo $this->db->insert_id(); //returns last inserted id

in one line

echo $this->db->insert('mytable',$data)->insert_id();
Spidy
  • 1,137
  • 3
  • 28
  • 48
Narsimha
  • 31
  • 1
2

You can get the latest inserted id by the in built php function mysql_insert_id();

$id = mysql_insert_id();

you an also get the latest id by

$id = last_insert_id();
Smern
  • 18,746
  • 21
  • 72
  • 90
Rahul
  • 45
  • 1
2

It's sad not to see any answers with an example.

Using Mysqli::$insert_id:

$sql="INSERT INTO table (col1, col2, col3) VALUES (val1, val2, val3)";
$mysqli->query($sql);
$last_inserted_id=$mysqli->insert_id; // returns last ID

Using PDO::lastInsertId:

$sql="INSERT INTO table (col1, col2, col3) VALUES (val1, val2, val3)";
$database->query($sql);
$last_inserted_id=$database->lastInsertId(); // returns last ID
Ikhlak S.
  • 8,578
  • 10
  • 57
  • 77
1

NOTE: if you do multiple inserts with one statement mysqli::insert_id will not be correct.

The table:

create table xyz (id int(11) auto_increment, name varchar(255), primary key(id));

Now if you do:

insert into xyz (name) values('one'),('two'),('three');

The mysqli::insert_id will be 1 not 3.

To get the correct value do:

mysqli::insert_id + mysqli::affected_rows) - 1

This has been document but it is a bit obscure.

Jimmy Kane
  • 16,223
  • 11
  • 86
  • 117
bartonlp
  • 123
  • 1
  • 6
1

I prefer use a pure MySQL syntax to get last auto_increment id of the table I want.

php mysql_insert_id() and mysql last_insert_id() give only last transaction ID.

If you want last auto_incremented ID of any table in your schema (not only last transaction one), you can use this query

SELECT AUTO_INCREMENT FROM information_schema.TABLES
    WHERE TABLE_SCHEMA = 'my_database' 
    AND TABLE_NAME = 'my_table_name';

That's it.

syjust
  • 327
  • 2
  • 4
  • i am doubtfull about this, as this SQL is simply wrong in context of the question.... Also this method feels prone to possible race conditions when two or more clients executes this SQL at around the same time... i am not sure how fast this column data is updated after a insert which makes me doubtfull .. . The PHP functions which can get the last id are based on connection/session level (does more or less the same as MySQL's [LAST_INSERT_ID()](https://dev.mysql.com/doc/refman/8.0/en/information-functions.html#function_last-insert-id)) which makes it race condition save – Raymond Nijland Oct 08 '19 at 10:29
0

Using MySQLi transaction I sometimes wasn't able to get mysqli::$insert_id, because it returned 0. Especially if I was using stored procedures, that executing INSERTs. So there is another way within transaction:

<?php

function getInsertId(mysqli &$instance, $enforceQuery = false){
    if(!$enforceQuery)return $instance->insert_id;

    $result = $instance->query('SELECT LAST_INSERT_ID();');

    if($instance->errno)return false;

    list($buffer) = $result->fetch_row();

    $result->free();

    unset($result);

    return $buffer;
}

?>
BlitZ
  • 12,038
  • 3
  • 49
  • 68
0

Use mysqli as mysql is depricating

<?php
$mysqli = new mysqli("localhost", "yourUsername", "yourPassword", "yourDB");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}
// Conside employee table with id,name,designation
$query = "INSERT INTO myCity VALUES (NULL, 'Ram', 'Developer')";
$mysqli->query($query);

printf ("New Record has id %d.\n", $mysqli->insert_id);

/* close connection */
$mysqli->close();
?>
Poorna Rao
  • 335
  • 4
  • 20
-1

I tried

mysqli_insert_id($dbConnectionObj)

This returns the current connection's last inserted id, so if you are managing your connections properly this should work. Worked for me at least.

Vega
  • 27,856
  • 27
  • 95
  • 103