php / mysql - need to find out id of last inserted row

Soldato
Joined
4 Jul 2004
Posts
2,647
Location
aberdeen
hi
how can ifind out the last id (or last value for the primary key in a table) for a query i just entered?
i want to do something like:
insert into reviews (id', 'intro') values (null, '$intro' etc)

then something like:
insert into games ('id', 'reviewid') values (null, '$idfrompreviousquery')

(i know those queries are not correct, just to give a basic idea)

cheers
 
I do it this way


PHP:
$new_sql = "select MAX(id) from reviews";
$get_new_sql= mysql_query($new_sql) or die(mysql_error());
$new_id = mysql_result($get_new_sql,"id");

that is how i would do it anyway
 
the way i did it only queires once, but i suppose Goksly is better. :confused:

my way works for me :) just thought i would share how i do it
 
NaTe said:
I do it this way


PHP:
$new_sql = "select MAX(id) from reviews";
$get_new_sql= mysql_query($new_sql) or die(mysql_error());
$new_id = mysql_result($get_new_sql,"id");

that is how i would do it anyway
Look into "race conditions" :)
 
Sorry, what I meant was you still have to do the insert query and then the select max query.
Whereas the other way you just do the insert. :)


Edit, and I guess beansprout is saying that inbetween the 2 queries someone else may have jumped in and inserted another record - thus returning the wrong record in the select max query... Possible, I guess!
 
Last edited:
KingAdora said:
Edit, and I guess beansprout is saying that inbetween the 2 queries someone else may have jumped in and inserted another record - thus returning the wrong record in the select max query... Possible, I guess!
Correct, and very possible :)
 
that is a very good point and something i never really thought about. I guess i have always thought that it is execusted quick enough to not cause a problem.

Thank you for pointing that out! :)
 
selecting the max id with a reviewer name (assuming they have to have one) will stop that error being possible -> unless the guy has a split personality :p
 
dual sessions is not eliminated by that process.

It's also less efficient than using mysql_insert_id() which is there for this exact purpose, so using anything else is just plain.. silly.
 
Back
Top Bottom