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

2018-12-31 02:42发布

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?

标签: php mysql
22条回答
伤终究还是伤i
2楼-- · 2018-12-31 03:16

Use mysql_insert_id() function.

See similar question here

查看更多
浮光初槿花落
3楼-- · 2018-12-31 03:17

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.

查看更多
人间绝色
4楼-- · 2018-12-31 03:20

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();
查看更多
爱死公子算了
5楼-- · 2018-12-31 03:21

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.

查看更多
冷夜・残月
6楼-- · 2018-12-31 03:22

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.

查看更多
查无此人
7楼-- · 2018-12-31 03:22

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();
?>
查看更多
登录 后发表回答