简体   繁体   English

如何在 PHP 中获取 MySQL 表的最后插入 ID?

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

I have a table into which new data is frequently inserted.我有一个经常插入新数据的表。 I need to get the very last ID of the table.我需要获取表的最后一个 ID。 How can I do this?我怎样才能做到这一点?

Is it similar to SELECT MAX(id) FROM table ?它类似于SELECT MAX(id) FROM table吗?

If you're using PDO, use PDO::lastInsertId .如果您使用 PDO,请使用PDO::lastInsertId

If you're using Mysqli, use mysqli::$insert_id .如果您使用的是 Mysqli,请使用mysqli::$insert_id

If you're still using Mysql:如果您仍在使用 Mysql:

Please, don't use mysql_* functions in new code . 请不要在新代码中使用mysql_*函数 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.了解准备好的语句,并使用PDOMySQLi -本文将帮助您决定哪个。 If you choose PDO, here is a good tutorial .如果您选择 PDO,这里有一个很好的教程

But if you have to, use mysql_insert_id .但如果必须,请使用mysql_insert_id

there is a function to know what was the last id inserted in the current connection有一个函数可以知道当前连接中插入的最后一个 id 是什么

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.加上使用max是一个坏主意,因为如果您的代码在两个不同的会话中同时使用,它可能会导致问题

That function is called mysql_insert_id该函数称为mysql_insert_id

It's ok.没关系。 Also you can use LAST_INSERT_ID()你也可以使用LAST_INSERT_ID()

With PDO :使用PDO

$pdo->lastInsertId();

With Mysqli :使用Mysqli

$mysqli->insert_id;

Please, don't use mysql_* functions in new code . 请不要在新代码中使用mysql_*函数 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.了解准备好的语句,并使用PDOMySQLi -本文将帮助您决定哪个。 If you choose PDO, here is a good tutorial .如果您选择 PDO,这里有一个很好的教程

Use mysql_insert_id() function. 使用mysql_insert_id()函数。

See similar question here 在这里看到类似的问题

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.假设您编写的内容是唯一且自动递增的,那么您编写的内容将为您提供最大的id ,假设您可以接受并发问题。
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.由于您使用 MySQL 作为数据库,因此有特定的函数LAST_INSERT_ID()仅适用于执行插入操作的当前连接。
PHP offers a specific function for that too called mysql_insert_id . PHP 也为此提供了一个特定的函数,称为mysql_insert_id

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);

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在 codeigniter 中获取最后插入的 id 执行插入查询后,只需在数据库上使用一个名为insert_id()函数,它将返回最后插入的 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();

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.可以使用mysql_insert_id() ,但有一个关于使用它的特定注意事项,您必须在执行 INSERT 查询后调用它,意味着在同一个脚本会话中。 If you use it otherwise it wouldn't work correctly.如果您使用它,否则它将无法正常工作。

You can get the latest inserted id by the in built php function mysql_insert_id();您可以通过内置的php函数mysql_insert_id();获取最新插入的id mysql_insert_id();

$id = mysql_insert_id();

you an also get the latest id by您还可以通过以下方式获得最新的 ID

$id = last_insert_id();

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'];

NOTE: if you do multiple inserts with one statement mysqli::insert_id will not be correct.注意:如果你用一个语句进行多次插入,mysqli::insert_id 将不正确。

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. mysqli::insert_id 将是 1 而不是 3。

To get the correct value do:要获得正确的值,请执行以下操作:

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

This has been document but it is a bit obscure.这是文档,但有点晦涩。

I prefer use a pure MySQL syntax to get last auto_increment id of the table I want.我更喜欢使用纯 MySQL 语法来获取我想要的表的最后一个 auto_increment id。

php mysql_insert_id() and mysql last_insert_id() give only last transaction ID. php mysql_insert_id() 和 mysql last_insert_id() 只给出最后一个事务 ID。

If you want last auto_incremented ID of any table in your schema (not only last transaction one), you can use this query如果您想要架构中任何表的最后一个 auto_incremented ID(不仅是最后一个事务),您可以使用此查询

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

That's it.就是这样。

It's sad not to see any answers with an example.很遗憾没有看到任何带有示例的答案。

Using Mysqli::$insert_id :使用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 :使用PDO::lastInsertId

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

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 INSERT s.使用MySQLi事务我有时无法获得mysqli::$insert_id ,因为它返回 0。特别是如果我使用存储过程,即执行INSERT s。 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;
}

?>

Use mysqli as mysql is depricating使用mysqli因为mysql正在贬低

<?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();
?>

Please use PDP and then try this 请使用PDP,然后尝试

$stmt = $db->prepare("...");
$stmt->execute();
$id = $db->lastInsertId();

By all this discussion I assume that the reason to check max id is to know what id should be next.. (if my max id is 5 then next will be 5+1=6). 通过所有这些讨论,我认为检查最大ID的原因是要知道下一个ID是什么(如果我的最大ID是5,则下一个将是5 + 1 = 6)。

>>If this is not the reason, my best apologies >>如果不是这个原因,我最好的歉意

Case if someone else INSERTs information between your CHECK and INSERT would give you wrong ID. 如果其他人在您的CHECK和INSERT之间插入信息会给您错误的ID。

So It can be solved if you would create hash that could include timestamp or other unique value. 因此,可以解决是否创建包含时间戳或其他唯一值的哈希。

Then in the same function you can insert your information with empty values and your hash. 然后,在同一函数中,您可以使用空值和哈希值插入信息。 That would create ID if you have AUTO_INCRECEMENT selected. 如果您选择了AUTO_INCRECEMENT,则将创建ID。

Then in the same function you would still have your hash and you could look for id with the same hash. 然后,在相同的函数中,您仍将拥有哈希,并且可以使用相同的哈希查找id。 And then you could complete populating empty values with mysql UPDATE. 然后,您可以使用mysql UPDATE完成填充空值。

This includes a bit more connections, but it is still a way to do it... 这包括更多的连接,但仍然是一种方法。

Good luck solving it. 祝你好运解决它。

$ lastid = mysql_insert_id();

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.这将返回当前连接的最后插入的 id,因此如果您正确管理您的连接,这应该可以工作。 Worked for me at least.至少为我工作。

Try this:尝试这个:

$sql = "INSERT INTO table_name VALUES (nininini)";
mysqli_query($connection, $sql);
mysqli_insert_id($connection);

If your table have AUTO INCREMENT column like UserID,Emp_ID,.. then you can use this query to get last inserted record SELECT * FROM table_name where UserID=(select MAX(UserID)from table_name) In PHP code: 如果您的表具有AUTO INCREMENT列(如UserID,Emp_ID等),则可以使用此查询获取最后插入的记录SELECT * FROM table_name,其中UserID =(从table_name选择MAX(UserID))在PHP代码中:

$con = mysqli_connect('localhost', 'userid', 'password', 'database_name');
                                if (!$con) {
                                    die('Could not connect: ' . mysqli_error($con));
                                }
                                $sql = "SELECT * FROM table_name where UserID=(select MAX(UserID)from table_name)";
                                $result = mysqli_query($con, $sql);

Then you can use fetched data as your requirement 然后,您可以使用提取的数据作为需求

mysql_query("INSERT INTO mytable (product) values ('kossu')");

printf("Last inserted record has id %d\n", ***mysql_insert_id()***);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM