Not getting last insert id

Do you have a question? Post it now! No Registration Necessary.  Now with pictures!

Threaded View
Hello everyone,

I am using a custom php class where i have wrapped all the mysql
connection settings and query functions. Instead of calling direct
mysql functions i creat an instance of this class and than use the
custon functions for query, connection etc. At some places i also use
direct php mysql functions to connect and query.

My problem is that on my web site sometime i dont get last insert id of
an insert query. Is it because connections are shared or is there some
other problem. If i force mysql to always open a new connection for
query will it overload my server. Can anyone give me any solutions.

All suggestions are welcomed.


Re: Not getting last insert id wrote:

Quoted text here. Click to load it

Are you calling the insert and "get last id" within the same connection?

"These functions are connection-specific, so their return values are not
affected by another connection which is also performing inserts."

Re: Not getting last insert id wrote:
Quoted text here. Click to load it

I can't tell for certain because I haven't seen your code.  But here's
my educated guess about the explanation:

I assume you're using PHP in an Apache environment, and each Apache
worker thread has its own persistent connection to the MySQL database.

The value returned by LAST_INSERT_ID() in MySQL is available only in the
scope of the database connection in which the insert was done that
created that ID.

The tricky thing is that subsequent HTTP requests (that is, page loads)
are not guaranteed to be handled by the same Apache worker thread.

So if you're inserting a record in one PHP request, and then in a
subsequent PHP request expecting to use LAST_INSERT_ID() to fetch that
value, you might not be able to.

Forcing a given Apache worker thread to handle subsequent requests for a
particular web client is called "session affinity" and it is not a
typical function of Apache.  Though you might be able to find a patch
for it, for instance .

The best solution is to use the LAST_INSERT_ID() immediately, during the
same PHP page that inserted the record originally.

Bill K.

Site Timeline