使用php在mysql中查找最后插入的ID的最佳方法 [英] Best way to find the last inserted ID in mysql using php
问题描述
我想知道最好的解决方案是在mysql查询后获取最后插入的ID吗?
Im wondering as to what the best solution is to get the last inserted ID after a mysql inquiry?
我找到了以下解决方案:
I have found the following solutions :
<?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查询,则可能不可靠.
or even using mysql_insert_id
php function, but apparently this function will not work well with bigint (thats what I am using for ID field) and if there are alot of consecutive sql inquiries it could be unreliable.
有人可以提供可靠且快速的解决方案来完成此任务吗?
Could someone provide a reliable and fast solution to achieve this task?
推荐答案
SELECT LAST_INSERT_ID()
是否不够可靠和安全?
Isn't SELECT LAST_INSERT_ID()
reliable and safe enough?
From 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.
来自论坛的说明: (...)您正在使用持久连接,例如通过mysql_pconnect()(...)
这篇关于使用php在mysql中查找最后插入的ID的最佳方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!