This function comes in handy if you need to know the key or index of the last insert into your mysql database. Other methods just don’t cut it.
By using mysql_insert_id() you will get the id of the last inserted statement.
/* Say you enter a new row into your database
After you have finished the insert statement you would do something like this.*/
$lastId = mysql_insert_id();
So why do I say other methods don’t cut it? When you thing about it, a lot of people just run into problems counting the number of rows in the database, and then obviously the next one would be the new one. This is a BAD IDEA!!! Consider the following example.
// rows in a table
1 carlos
2 suzy
3 jack
4 robert
5 mary
// If we insert another record, we can assume it will be 6.
6 fred
// If we counted the rows it would work fine.
// What happens when suzy doesnt like us and wants her name removed?
// We now have a list like this
1 carlos
3 jack
4 robert
5 mary
6 fred
// Now if we want to submit sam, using the row counting method we would say his id is 6 but in actuality it will be 7.
Because we dont want to mix up sam’s id with freds, we have to use the mysql_insert_id.
Tweet This Post