替代“PDO::lastInsertId"/"mysql_insert_id" [英] Alternative to "PDO::lastInsertId" / "mysql_insert_id"

查看:58
本文介绍了替代“PDO::lastInsertId"/"mysql_insert_id"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我总是听说使用lastInsertId"(或 mysql_insert_id() 如果您不使用 PDO)是邪恶的.在触发器的情况下,它显然是,因为它可能返回完全不是您的 INSERT 创建的最后一个 ID 的内容.

I always hear that using "lastInsertId" (or mysql_insert_id() if you're not using PDO) is evil. In case of triggers it obviously is, because it could return something that's totally not the last ID that your INSERT created.

$DB->exec("INSERT INTO example (column1) VALUES ('test')");
// Usually returns your newly created ID.
// However when a TRIGGER inserts into another table with auto-increment:
// -> Returns newly created ID of trigger's INSERT
$id = $DB->lastInsertId();

有什么选择?

推荐答案

如果走 ADOdb (http://adodb.sourceforge.net/),然后您可以事先创建插入 ID,并在插入时明确指定 ID.这可以移植地实现(ADOdb 支持大量不同的数据库......)并保证您使用正确的插入 ID.

If you go the route of ADOdb (http://adodb.sourceforge.net/), then you can create the insert ID before hand and explicitly specific the ID when inserting. This can be implemented portably (ADOdb supports a ton of different databases...) and guarantees you're using the correct insert ID.

PostgreSQL SERIAL 数据类型是类似的,除了它是按表/按序列,您在请求时指定您希望最后插入 ID 的表/序列.

The PostgreSQL SERIAL data type is similar except that it's per-table/per-sequence, you specify the table/sequence you want the last insert ID for when you request it.

这篇关于替代“PDO::lastInsertId"/"mysql_insert_id"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆