Alternative to “PDO::lastInsertId” / “mysql_insert

2019-03-28 06:59发布

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

What's the alternative?

6条回答
我只想做你的唯一
2楼-- · 2019-03-28 07:28

You could try this:

$sql = "SELECT id FROM files ORDER BY id DESC LIMIT 1";
$PS = $DB -> prepare($sql);
$PS -> execute();
$result = $PS -> fetch();
查看更多
【Aperson】
3楼-- · 2019-03-28 07:29

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.

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.

查看更多
劳资没心,怎么记你
4楼-- · 2019-03-28 07:32

I guess it's not really state of the art either but I use write locks to make sure that I really get the last inserted ID.

查看更多
家丑人穷心不美
5楼-- · 2019-03-28 07:36

One alternative is to use sequences instead, so you generate the ID yourself before you do the insert.

Unfortunately they are not supported in MySQL but libraries like Adodb can emulate them using another table. I think however, that the emulation itself will use lastInsertId() or equivalent... but at least you are less likely to have a trigger on a table which is purely used for a sequence

查看更多
贼婆χ
6楼-- · 2019-03-28 07:37

IMHO it's only considered "evil" because hardly any other SQL database (if any) has it.

Personally I find it incredibly useful, and wish that I didn't have to resort to other more complicated methods on other systems.

查看更多
混吃等死
7楼-- · 2019-03-28 07:38

It's not sophisticated and it's not efficient, but if the data you've inserted include unique fields, then a SELECT can obviously yield what you're after.

For example:

INSERT INTO example (column1) VALUES ('test');
SELECT id FROM example WHERE column1 = 'test';
查看更多
登录 后发表回答