使用php在mysql中查找最后插入的ID的最佳方法 [英] Best way to find the last inserted ID in mysql using php

查看:92
本文介绍了使用php在mysql中查找最后插入的ID的最佳方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道最好的解决方案是在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?

从MySQL Doc: 所生成的ID在服务器上按以下方式维护:连接基础.这意味着函数返回给定客户端的值是为该客户端影响AUTO_INCREMENT列的最新语句生成的第一个AUTO_INCREMENT值.即使其他客户端生成自己的AUTO_INCREMENT值,该值也不会受到其他客户端的影响.

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屋!

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