Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

how to get primary key value after just creating it... 1

Status
Not open for further replies.

spewn

Programmer
May 7, 2001
1,034
i'm using this to create a new row in my database:

Code:
$sth2 = $dbh->prepare("INSERT INTO emailgroup1 VALUES(0,'$userFirstName','$userLastName','$userEmail','','','','','','')");
$sth2->execute;

it automatically increments the primary key, the first value, and i need to find out the value, (number) of that key...how is this possible?

- g
 
i'm actually using perl...

i tried this:

$id = $query->insertid;

but i'm getting this error:

Can't call method "insertid" on an undefined value at send-email.cgi line 39.

no ideas?

- g
 
You could select the latest table entry, like this.
The auto increment field is called NUM.
Code:
my $make_blank=$dbh->prepare("INSERT INTO TABLE VALUES ()");
$make_blank->execute();

my $get_number=$dbh->prepare("SELECT NUM FROM TABLE ORDER BY NUM DESC");
$get_number->execute();
@FILENUM=$get_number->fetchrow_array();

Keith
 
keith, don't do that, you will end up in a race condition :)

another way to approach the problem is to recognize that the auto_increment is a surrogate key and that the table should have another candidate key which uniquely identifies each row

thus, you can simply query the row back using the value of this other key

but LAST_INSERT_ID() is the best way to go here

r937.com | rudy.ca
 
Not sure I understand how this sets up a race condition.
A new record is created then the value is read. I have used this method without problems, have I been lucky?

Keith
 
yes, lucky

user 1 inserts into the table, getting auto_increment value 42

user 2 inserts into the table, getting auto_increment value 43

user 1 runs the select for the highest num and gets 43

user 2 runs the select for the highest num and gets 43

did you read that article? ;-)


r937.com | rudy.ca
 
Thanks for the explanation.
I hadn't considered the multiple thread possibility. I had to do a bit of reading elsewhere to get a grip of it but what you said now makes sense. I guess I am too used to a low traffic environment and the possibility of two users adding files together has not yet happened. I can see the headaches that could cause where some data just disappears. Hava a star for saving me future problems.
What would LAST_INSERT_ID() return if the table did not have auto increment set?

Keith
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top