MorkaLork Development

Interesting stuff I've picked up over the years...


2009-04-17 07:35:57 | 197 views | mysql_insert_id mysql_insert_id() id get id auto_increment identity

Retrieving auto incremented values

If you have a table with an primary key that auto increments you might want to retrieve the number that has been generated for that record. Then the mysql_insert_id() just might come in hand.



int mysql_insert_id ([ resource $link_identifier ] )


//Create a connection
$link = mysql_connect("", "maffelu", "xeno2409");
//Select database
mysql_select_db("examples", $link);
//Create a query
$sql = "INSERT INTO Person (Name, Age, Gender) VALUES ('Olov', 21, 'Male')";
//Execute the query
$result = mysql_query($sql, $link);

//If correct, output result
echo "The last inserted record has id ".mysql_insert_id();
//If the query was unsucceful, we will output the error
echo "<b>Error ".mysql_errno($link).":</b> ".mysql_error($link);
//Close the connection


The last inserted record has id 2

Our table previously only has one record, it had the id of 1. If we did this again we would get id 3 back. Simple enough.

Article comments

Feel free to comment this article using a facebook profile.

I'm using facebook accounts for identification since even akismet couldn't handle all the spam I receive every day.