如何在 PHP 中获取 MySQL 表的最后插入 ID? [英] How do I get the last inserted ID of a MySQL table in PHP?
问题描述
我有一个经常插入新数据的表.我需要获取表的最后一个 ID.我该怎么做?
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?
是否类似于SELECT MAX(id) FROM table
?
推荐答案
如果您使用 PDO,请使用 PDO::lastInsertId
.
If you're using PDO, use PDO::lastInsertId
.
如果您使用的是 Mysqli,请使用 mysqli::$insert_id
.
If you're using Mysqli, use mysqli::$insert_id
.
如果你还在使用 Mysql:
If you're still using Mysql:
请不要使用mysql_*
新代码中的函数.它们不再维护并正式弃用.看到红框?了解准备好的语句,并使用PDO 或 MySQLi -
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.
但是如果必须的话,使用 mysql_insert_id
.
这篇关于如何在 PHP 中获取 MySQL 表的最后插入 ID?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!