简体   繁体   English

PDO lastInsertId(); ? 从刚刚插入的值的特定列返回值

[英]PDO lastInsertId(); ? return value from specific column of just inserted value

I need to return the value from my auto incremented column of the update that's just happened. 我需要从刚刚发生的更新的自动递增列中返回值。

Basically I am updating a user with XYZ values: 基本上,我正在使用XYZ值更新用户:

$stmt->execute();

I need to get the new records value from ID column in the database which is auto incremented. 我需要从数据库的ID列获取新记录的值,该值会自动递增。

PDO lastInsertId(); PDO lastInsertId(); just returns the latest record and could be potentially dangerous on a high traffic site? 只是返回最新记录,并且在人流量大的网站上可能有潜在危险吗?

I hope you are using MySql?? 希望您使用的是MySql?

From mysql site: 从mysql站点:

The ID that was generated is maintained in the server on a per-connection basis. 生成的ID在每个连接的服务器中维护。 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. 这意味着函数返回给定客户端的值是针对该客户端影响AUTO_INCREMENT列的最新语句生成的第一个AUTO_INCREMENT值。 This value cannot be affected by other clients, even if they generate AUTO_INCREMENT values of their own. 即使其他客户端生成自己的AUTO_INCREMENT值,该值也不会受到其他客户端的影响。 This behavior ensures that each client can retrieve its own ID without concern for the activity of other clients, and without the need for locks or transactions. 此行为可确保每个客户端都可以检索自己的ID,而不必担心其他客户端的活动,也不需要锁或事务。

Further: 进一步:

If you insert multiple rows using a single INSERT statement, LAST_INSERT_ID() returns the value generated for the first inserted row only. 如果使用单个INSERT语句插入多行,则LAST_INSERT_ID()仅返回为第一个插入行生成的值。

So it's save to use because it works on connection basis. 因此节省了使用时间,因为它基于连接工作。 And if you insert multiple rows you can combine it with PDO's rowCount method to get all inserted id's. 而且,如果您插入多行,则可以将其与PDO的rowCount方法结合使用,以获取所有插入的ID。

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

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