Finding the ID of a Newly Inserted MySQL Row

If you’re anything like me, you generally set up an auto-incrementing integer field in most of your MySQL tables that can be used as the primary key for your records. A lot of times, after inserting new information into the database, you need a way to find out what ID was assigned to your data when you created the new row. With MySQL, it’s really simple to get that information. MySQL offers a function called “LAST_INSERT_ID” that does just that.

As soon as you finish inserting the new row, if you run another SQL query that looks like “SELECT LAST_INSERT_ID()” on your database, the result you get back will be the most recently added auto-increment number in your MySQL installation.

PHP also has a built-in function to perform this operation. Instead of setting up a separate MySQL query, executing it and retrieving the results from it, you can simply use the mysql_insert_id() function, which will automatically perform those steps and simply return the ID number.

Did you like this post? Get monthly summary of our new tutorials, posts and tips to your inbox!

No Responses

Post Your Comment

Your email address will not be published.