astralaaron Posted June 8, 2008 Share Posted June 8, 2008 How can I find out the last id# in a mysql table? the id is the primary key auto incrementing. basically i'm adding information to a table from a form and it creates a new row with a new ID, right after the row is added I need to be able to insert data into a different table (a relative table) with the ID of the row that I just created - please let me know!I am thinking right now that I can do mysql_num_rows and get a count of them, but the 0 is throwing me off - will ID# 40 be count 39? Link to comment Share on other sites More sharing options...
Wander Posted June 8, 2008 Share Posted June 8, 2008 mysql_num_rows shows the amount of rows, so if u remove a row it will lower, while the auto increment thingy wont loweryou can use the function mysql_insert_id() but i think that only works after you just inserted somethingjust getting the auto increment value can be done with:$result = mysql_query("SHOW TABLE STATUS FROM `database` WHERE `Name`='table';");$row = mysql_fetch_assoc($result);echo $row['Auto_increment']; Link to comment Share on other sites More sharing options...
Jesdisciple Posted June 8, 2008 Share Posted June 8, 2008 Yes, if the 1st is 0 the 40th will be 39. y = x - 1 So if the row you just added is the last (i.e. no other processes are inserting into or deleting from that table), the table's length minus one is that row's ID. Link to comment Share on other sites More sharing options...
astralaaron Posted June 8, 2008 Author Share Posted June 8, 2008 thanks Link to comment Share on other sites More sharing options...
astralaaron Posted June 8, 2008 Author Share Posted June 8, 2008 i just thought of a problem with that though, they can actually remove the events at future times ... so the ID count probably wont work..i've never used the show table status, that looks like it might work.*EDIT I just realized Wander already pointed that out above. Link to comment Share on other sites More sharing options...
astralaaron Posted June 8, 2008 Author Share Posted June 8, 2008 $result = mysql_query("SHOW TABLE STATUS FROM `database` WHERE `Name`='table';");$row = mysql_fetch_assoc($result);echo $row['Auto_increment']; I'm trying to understand the above code, that is going to give me the last auto increment? Link to comment Share on other sites More sharing options...
shadowayex Posted June 9, 2008 Share Posted June 9, 2008 How about something like this:$row = mysql_query("SELECT * FROM your table ORDER BY primary key column DESC LIMIT 1");$row = mysql_fetch_array($row);echo = $row['primary key column']; Link to comment Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.