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条回答
查无此人
2楼-- · 2018-12-31 03:33

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'];
查看更多
临风纵饮
3楼-- · 2018-12-31 03:34

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.

查看更多
唯独是你
4楼-- · 2018-12-31 03:37

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

查看更多
大哥的爱人
5楼-- · 2018-12-31 03:39
mysql_query("INSERT INTO mytable (product) values ('kossu')");

printf("Last inserted record has id %d\n", ***mysql_insert_id()***);
查看更多
登录 后发表回答