我想知道什么是最好的解决方案是在mysql查询后获取最后插入的ID?

我发现以下解决方案:

<?php
function get_current_insert_id($table)
{
    $q = "SELECT LAST_INSERT_ID() FROM $table";
    return mysql_num_rows(mysql_query($q)) + 1;
}
?>

甚至使用mysql_insert_id php函数,但显然此函数不能与bigint配合使用(这是我用于ID字段的功能),并且如果有大量连续的SQL查询,则可能不可靠。

有人可以提供可靠且快速的解决方案来完成此任务吗?

最佳答案

SELECT LAST_INSERT_ID()不够可靠和安全吗?

从MySQL Doc:
The ID that was generated is maintained in the server on a per-connection basis. 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. This value cannot be affected by other clients, even if they generate AUTO_INCREMENT values of their own.

来自论坛的注释:
(...)All bets are off, though, if for some reason you are using persistent connections, such as via mysql_pconnect()(...)

10-06 07:36
查看更多