Jump to content

[SOLVED] Getting an auto-incremented primary key from a newly INSERTed row.


Recommended Posts

Hello,

 

I have a typical table called userdata, it has an auto-incrementing unsigned integer primary key named userdataid, and a bunch of other columns storing various data (firstname, lastname, gender, location, occupation, website, email, etc...). 

 

When I create a new user, I have to create their associated data, and insert those values into a new row in the userdata table.  Since the primary key auto-increments, (basically setting itself on an INSERT statement, right?) my question is, how do I find out what the userdataid primary key was set to after creating a new row?

 

for example:

INSERT INTO userdata(firstname, lastname, location) VALUES('default', 'default', 'default');

 

If I run this statement for a new user, a new row gets created and inserted into the userdata table.  This new row has a userdataid value that I need to get at.  One way to tackle this would be to run this statement:

 

SELECT userdataid, firstname, lastname, occupation FROM userdata WHERE firstname='default' and lastname='default' and occupation='default';

 

The problem with this is that if the user never updates their userdata from its default values, then this last statement will return a bunch of rows, not just the one that was last INSERTed, and I won't know which userdataid is the one I want to get at.

 

So, anyone know if I'm overlooking a simple solution here, or if I'm going about this wrong?

 

Thanks in advance!

 

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.