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

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

问题描述

我总是听到使用"lastInsertId"(如果不使用PDO,则使用mysql_insert_id())是邪恶的.如果是触发器,则显然是这样,因为它可能返回的内容完全不是您的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天全站免登陆