MorkaLork Development

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

Mysql_insert_id()

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.

PHP.NET

http://se2.php.net/mysql_insert_id

Syntax:

int mysql_insert_id ([ resource $link_identifier ] )

Example:



<?php
//Create a connection
$link = mysql_connect("db.telana.com", "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($result)
{
//If correct, output result
echo "The last inserted record has id ".mysql_insert_id();
}
else
{
//If the query was unsucceful, we will output the error
echo "<b>Error ".mysql_errno($link).":</b> ".mysql_error($link);
}
//Close the connection
mysql_close($link);
?>



Output:

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.